Reputation: 1065
I would like to get file attributes in C on cross platform. I tried stat
and access
, they both work fine on Unix-like systems (Ubuntu, Mac OS X). But this commands misbehave on Windows, for example: whether there is read permission for file or not, stat
and access
both always return true.
Here is my function, which works correctly on Unix-like systems.
int is_readable(char *file)
{
struct stat fileStat;
stat(file, &fileStat);
return (fileStat.st_mode & S_IRUSR);
}
What is the right way of getting file attributes in C on Windows (cross platform solution would be even better)?
Upvotes: 0
Views: 896
Reputation: 561
File permissions on unix like systems and windows are completely different. So I think, the easiest is simply try reading the file and deal with the errno/return code.
Upvotes: 2
Reputation: 399833
On Win32, access()
really should work. I suspect you used it wrong, it returns 0 on success. The documentation is pretty clear:
Each function returns 0 if the file has the given mode. The function returns –1 if the named file does not exist or does not have the given mode; [...]
It's easy to incorrectly interpret -1
as true
; you must compare against 0
.
Also, I would argue that your function doesn't work correctly, it doesn't handle the case when stat()
fails. I/O is brittle, you must error-check!
Upvotes: 1