3

On linux, the close() function may fail and errno is set. I guess something similar happens on other systems. Is there a way in the standard library to access the error information on a failed file closing operation? For example:

std::fstream fs(path);
fs.close(); // <-- suppose this fails

How do I know what caused the error? (in a portable way if possible)

DeltA
  • 564
  • 4
  • 12
  • 2
    Really hard to say, but you can probably still check `errno` because sooner or later it's going almost certainly going to call `fclose`. I'm all for always checking the return state/return code, but in this case I'm not sure what kind of diagnostic information you can get on a failed close or what you can do about it. This is one thing I generally let slide. – user4581301 Sep 17 '21 at 23:57
  • Quoting [cppreference](https://en.cppreference.com/w/cpp/io/basic_filebuf/close): *Then, closes the file as if by calling `std::fclose()`, regardless of whether any of the preceding calls succeeded or failed.* Now I have to go diving in the Standard to see what kind of wiggle room is afforded by the *as if by*. – user4581301 Sep 18 '21 at 00:00
  • If an error occurs during operation, setstate(failbit) is called. that's all the standard gets you. no standard, but there may be some cumbersome cross-platform framework that does this kind of thing. – Abel Sep 18 '21 at 00:01
  • 1
    Standard uses the [same wording with no explanation.](http://eel.is/c++draft/file.streams#filebuf.members-8) That sucks. – user4581301 Sep 18 '21 at 00:05
  • 1
    only severe error that comes to mind is that any remaining write buffer did not flush. – Abel Sep 18 '21 at 00:07
  • I've searched for a while. It seems the common practice is not to care about failing closing operations, since you can't do anything about it. I still had some hope I missed something. – DeltA Sep 18 '21 at 00:08
  • Unix Man pages for `fclose` give more information, but that's useless as it can only be counted on with Unix. May be better information at Microsoft. – user4581301 Sep 18 '21 at 00:08
  • One thing I can think of is if you have the ability to delete a stale log file or clear space in a circular buffer and try again, but what I'm reading sounds like once you close, it's closed even though it failed and very possibly the only thing you can do is log that the error happened. If you still have the file contents in memory and can find some way to correct the issue, you can try to open the file and write again. – user4581301 Sep 18 '21 at 00:10
  • 1
    Just found this guy: [fclose return value check](https://stackoverflow.com/questions/1954273/fclose-return-value-check) – user4581301 Sep 18 '21 at 00:11
  • Try to open and close the file with any other API. It can let you more information. Also, try to check the 'fs' state before fs.close(). It can have errors on file open or read\write. – stanislav888 Sep 18 '21 at 01:24

0 Answers0