How can you check if a file is read-only

Started by
5 comments, last by badmoon 19 years, 5 months ago
Hi Does anyone know of a way to check if a file is read-only?
Advertisement
I belive if you try to open a read only file with the write flag on, you'll get an error.
Several. Most operating systems export file APIs that will enumerate file attributes, if your programming language can access those. If your programming language can't, then in general, if you can open a file for reading, but not for writing then it's probably read only.

If you want more specific advice, then maybe you should mention what OS and/or programming language you're using.
I'm looking for a solution in C++ under a windows platform. I'd like to write a simple windows console app that can go through a directory and recursively check all files to see if any are read-only. So maybe there's a function similar to fopen that can do the job or something in the win32 api?

By the way, one of the advice mentioned above was to attempt to open a file for writing - but won't this just overwrite the file with an empty one? I.e. when doing something like:
fopen( "file.txt", "wb" );

Maybe this helps:
MSDN - GetFileAttributes
Quote:Original post by badmoon
By the way, one of the advice mentioned above was to attempt to open a file for writing - but won't this just overwrite the file with an empty one? I.e. when doing something like:
fopen( "file.txt", "wb" );


Then don't open the file with "wb" or any other mode that calls for the destruction of existing file contents. For example, opening the file with "a" should open the file asking for write permission, but does not clobber the contents on open.

However, if you're fine with using OS dependent API calls, it's better to use GetFileAttributes() or GetFileAttributesEx() to determine if the read only flag is set.
Marvelous, thank you people

This topic is closed to new replies.

Advertisement