0

Say I call the function openFile in my main function:

int main() {
    FILE *fptr;
    char *file_name = "myfile.txt";
    fptr = openFile(file_name, 'r');
    // ...
}

FILE *openFile(char *name, char *mode) {
    FILE *file = fopen(name, mode);
    if (file == NULL) {
        fprintf(stderr, "Error opening file.\n");
        exit(1);
    }
    printf("Opened file.\n");
    return file;
}

If fopen encounters an error and returns NULL, would it be better practice to handle the error in that if block as shown in the code above, or would it be better to return (NULL) like fopen does and then handle the error upstream in my main function? Or is there another method that is better for handling errors?

  • Some best practices don't relate to the return value. Error messages should be reported to standard error, not standard output, and error messages should end with a newline, and you should report on the name of the file that could not be opened. Also, if you encounter an error, your program should not exit with status 0; that indicates success. On the whole, the status message (opened file) should include the file name; it certainly should end with a newline too. Generally, unless you are deliberately building up a line piecemeal or prompting, you should end outputs with newlines. – Jonathan Leffler Feb 07 '21 at 01:49
  • Per the documentation, if fopen fails it returns null and global variable errno contains the error code. exit() call seems a bit harsh, let the caller decide what to do – OldProgrammer Feb 07 '21 at 01:49
  • @JonathanLeffler Ah some of those issues (e.g. status code and newline) just happened to slip past me when I was writing it on the post, but they're fine in my original files. I'll edit the post so they don't become the main focus of any answers since they're not what my issue lies with. Thanks for pointing them out, though! I'm more interested in whether I should handle the error within that function or pass it upstream to my main function and handle it there. –  Feb 07 '21 at 01:53
  • It depends on what the defined purpose of the function is. If the intention is to allow calling code to use the returned handle without testing it, exiting is appropriate. If it is only required to report the failure (and success), then exiting is not appropriate. Both can be correct. Failing early and quickly is often a good strategy; it also tends to be simpler. You can debate whether the error printing is appropriate. Even more so, is the success message appropriate. I tend to use early exit. General purpose library functions should usually not report errors; `fopen()` doesn't! – Jonathan Leffler Feb 07 '21 at 01:59

0 Answers0