In my C++ program, I want to make sure i can write info to a file. How can I perform this check?
+2
A:
You use the stat() system call, which the purists will tell you doesn't exist unless you change the tags on your question.
Richard Pennington
2010-02-17 13:33:53
I don't think he's talking about the preprocessor. I think he's talking about pre-processing (actions before processing) a file.
Richard Pennington
2010-02-17 13:37:22
+4
A:
The only sure way to find if you can write to a file is to try to write to a file. It is possible, and even likely in some circumstances, that a file will have its permissions changed between calls to function such as stat and the actual write. Your code must deal with write failures anyway, so it makes sense to centralise the testing code there.
anon
2010-02-17 13:45:23
I don't disagree with checking for write errors, but It seems odd that you wouldn't do a pre-check to see if the file was writeable before starting an operation, if only to give a better error message to the user. (Get ready to gather diagnostic image, turn on Xray, write data to file, oops! permission denied: not good.)
Richard Pennington
2010-02-17 14:08:44
@Richard It may be odd, but I can honestly say I've never done it. I do of course check that calls to open() (or whatever) succeed.
anon
2010-02-17 14:13:12
@Neil: thinking about it, the open is sufficient for the case I gave also. All the stat() call is the ability to provide a more specific error message, e.g. "can't open file because it is read only".
Richard Pennington
2010-02-17 15:47:57