简体   繁体   中英

How to quit program, if fstream.open() failed in subfunction

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM