checking file (ofstream) for read-only

I've written a save function that writes data into an .xml file via ofstream. I would like to check if the file I want to write to is read-only (so I can throw an exception when this should occur). Can anyone tell me how I can check if a file is read-only?

Many thanks in advance!
I think the best you can do is test to see if the file successfully opened for writing or not. Unless you use some OS specific library.

1
2
3
4
5
6
7
8
9
10
std::ofstream ofs("output-file.txt");

if(ofs.is_open())
{
    // .. do your stuff
}
else
{
    // ... could not open file for output 
}
It works! I never thought of is_open() going as far as checking for 'open for writing'. Goes to show a programmer's worst enemy is making assumptions :)

Thank you for providing this elegant solution!
It is not foolproof. It could fail for other reasons. But it should suffice for most applications.
No it's probably not foolproof (few things are, right?). But in this application, it's the one thing that really needed to be accounted for. If it happens to throw for other reasons, that's not really a problem in my case.
(On a side note, maybe it's even a good thing that the exception will be thrown when the file fails to open for other reasons that I can't predict. It makes the code safer and more portable, I think. But I could be wrong, I'm still learning.)

Thanks again!
Topic archived. No new replies allowed.