Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if I have permissions to open a file without opening it on Linux in C?

Tags:

c

linux

I want to be able to check to see if a file could be opened on Linux (for read or for read and write). However I don't have control of the code which will be opening the file, so I can't do what I would normally do which is to open it and then handle the error.

I appreciate that there will always be race conditions on any check due to permissions changing after the call has returned but before the open call, but I'm trying to avoid some undesirable error logging from a library which I have no control over.

I'm aware of stat, but I'd prefer not to need to try to replicate the logic of checking user IDs and group IDs.

like image 207
Free Wildebeest Avatar asked Oct 23 '25 05:10

Free Wildebeest


2 Answers

You can use:

access("filename", R_OK);

or

euidaccess("filename", R_OK);

To check if your UID or EUID have read access to a respective file. (UID and EUID will be different if your are running setuid)

like image 106
Flexo Avatar answered Oct 24 '25 21:10

Flexo


Use euidaccess or access, although you almost certainly always want to use the former.

like image 21
Free Wildebeest Avatar answered Oct 24 '25 21:10

Free Wildebeest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!