Reputation: 115
When programming I often open and close files. I understand that when opening a file, it's important to check for errors to see if it did in fact open. I don't know of an instance though when closing a file would be an issue (except for maybe if opening the file did give an error and it went unchecked).
I'm currently programming in go, and under the os
package the .Close()
function can return an error if it needs to. I know in C++ this is possible as well.
So finally, my question is what circumstances would cause an error when trying to close a file?
Upvotes: 5
Views: 6527
Reputation: 73376
At OS level, things can also go wrong when closing files, especially if you have written to them (i.e. buffering issues, out of disk space, media removed, etc...).
The C++ fstream
has a void close()
function which doesn't return anything. The principle is that once you called close you can no longer use the stream whether there was an error or not. However when a closing error occurs, the fail bit is set, so that it can be detected, and the error code can be retrieved the usual way.
The C fclose()
returns an int
which shows if there was an error or not. If you want to know why it failed you have to get and analyze the errno
error code. It's not as self-explaining as a void function, but here also, you can't use the FILE* anymore after the closing call, whether there was an error or not.
Upvotes: 4
Reputation: 31467
Yes. Closing a file can cause an error/fail. See for example the errors that close(3)
can return - http://linux.die.net/man/3/close - stuff like filesystem corruption is one probable cause.
Often you can't really do much about it though other than log an error and know that your data is probably screwed (depending on the error) - you can rarely "fix it" except for maybe re-writing the data somewhere else if you still have it etc.
The language you are using (Go, C++, whatever) is irrelevant. If the filesystem is full, corrupt or someone has physically ripped out the harddrive, then your programming language just can't save you and close will fail and it is anybodys guess whether your data are safely stored somewhere or not.
Upvotes: 8