0

I try to open a file in a function in a class:

void openFile(){

    inputFile.open(inputFilename.c_str());

    if (inputFile.is_open()){
      inputFile.read(buffer, skipAtBegin);
    } else {
      cerr << "Cannot open file: " << inputFilename << endl;
      exitNow();
    }
}

In main() i would just return 1, but how can i do this in a sub-sub-function-class the best/simplest way??

Return 1 all steps up to main?

Use ecxeptions?

Any exit() commands?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Narodon
  • 3
  • 1
  • Yes. [`std::exit()`](http://en.cppreference.com/w/cpp/utility/program/exit). For exactly this purpose. – BoBTFish Jul 16 '13 at 12:50
  • Actually, yes. The exit(int) command. But I would suggest using exceptions, since they give you a chance to handle these kinds of errors. – Kourosh Jul 16 '13 at 12:51
  • I wouldn't recommend exiting in your `openFile` function. You should return some type of value, and handle that where `openFile` is called. Or use exceptions in the same fashion. – crush Jul 16 '13 at 12:51
  • Coming back all the way up to `main` is tedious, but can allow to properly dispose of any critical resources you might be using. `exit` will be enough most of the time otherwise. – Nbr44 Jul 16 '13 at 12:51
  • Throw an exception you catch near the top of your program stack. Display appropriate message and return from main. – Neil Kirk Jul 16 '13 at 12:52

1 Answers1

1

Usually there are three Options:

  1. Use exit. Quit the program.
  2. Use exception. Throw exceptions, handles elsewhere.
  3. Set global status variable. Set global status, and let other functions checkt the status and handle it.

Hope someone would come up with other options.

lulyon
  • 6,707
  • 7
  • 32
  • 49