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?