What is the cleanest way of unsuccessful grace when a file cannot be opened in C ++?

The program requires the file to run, but if for any numerous reasons it cannot be found or cannot be read, etc. - what is the cleanest way to exit the program?

+4
source share
4 answers

Failure, how do you fail in other cases:

  • The command line program displays an unreadable file (full path) and the exact reason for not being able to read it on Stderr and exit with an error code. The strerror() and perror() functions will help you verbalize the cause of the failure.
  • Gui will send an error message similar to the one above and exit after confirmation.
+7
source

If the file is needed and the missing file is abnormal, I would throw an exception. Then it will be processed at a higher level, where you can decide what to do with the problem. If the application absolutely cannot work without the file in question, I would simply terminate it gracefully with the corresponding error message to show the exact problem for its users.

And, of course, I would try to check this file in advance before allocating other resources. Thus, fewer unnecessary things are done and less unused resources to free from abnormal completion.

+4
source

This type of error message should always include:

  • name by which the program tried to open the file
  • the result of strerror(errno) on Unix, or the more confusing Windows equivalent.
+1
source

I think of these three steps:

First : print the file name with the appropriate error message.

Second : clear the resources that your program has done. free memory, closing pipes, closing sockets, deleting temporary files, canceling mutexes ....

Third : finish using exit() .

0
source

All Articles