Joe Shaw
Joe Shaw

Reputation: 22592

Best POSIX way to determine if a filesystem is mounted read only

If I have a POSIX system like Linux or Mac OS X, what's the best and most portable way to determine if a path is on a read-only filesystem? I can think of 4 ways off the top of my head:

Are there other ways I'm missing? If you needed to know if a filesystem was mounted read-only, how would you do it?

Upvotes: 7

Views: 6264

Answers (2)

shaver
shaver

Reputation: 157

utime(path, NULL);

If you have write perms, then that will give you ROFS or -- if permitted -- simply update the mtime on the directory, which is basically harmless.

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882226

You could also popen the command mount and examine the output looking for your file system and seeing if it held the text " (ro,".

But again, that's not necessarily portable.

My option would be to not worry about whether the file system was mounted read only at all. Just try and create your file and, if it fails, tell the user what the error was. And, of course, give them the option of saving it somewhere else.

You really have to do that sort of thing anyway since, in any scenario where there's even a small gap between testing and doing, you may find the situation changes (probably not to the extent of making an entire file system read only but, who knows, maybe there is (or will be in the future) a file system that allows this).

Upvotes: 2

Related Questions