1
    if (fclose(file1) != 0)
{
    printf("Cannot close file\n");
}

I learned that the return value for fclose() should always be checked. I read somewhere that if the file did not close properly, data could be lost. However, i am unsure how a situation like this could occur, or any other situations that are related. What could be done if such a situation happened?

asa
  • 47
  • 7
  • According to `man fclose` the only error it can return is `EBADF` - "The file descriptor underlying fp is not valid." – Eugene Sh. Dec 12 '16 at 20:04
  • Eugene is right. Trying to close a file which is already closed - that can happen if we don't enforce strict rules about who opens a file and who closes it. Ideally, opening and closing should be handled in the same function or module. – codeforester Dec 12 '16 at 20:07
  • 2
    @EugeneSh.You missed the following line: *The `fclose()` function may also fail and set `errno` for any of the errors specified for the routines `close(2)`, `write(2)` or `fflush(3)`.* – dbush Dec 12 '16 at 20:08
  • @dbush Ooops. That's the important one. – Eugene Sh. Dec 12 '16 at 20:09
  • 3
    I think the larger question is what action can you take if `fclose` fails? – dbush Dec 12 '16 at 20:12
  • @dbush Yes, i added that to the question. Thank you. – asa Dec 12 '16 at 20:17
  • 1
    a file on a removable device that has been removed by the user? (usb stick, floppy disk,...) – pm100 Dec 12 '16 at 20:18

0 Answers0