Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to check a file's existence and file permissions in linux using c++

Tags:

c++

boost

I am using boost::filesystem::exists() to check file's existence.

Is there a better way to do it?

Also how do I find file permissions ?

like image 722
user592796 Avatar asked Feb 05 '11 16:02

user592796


People also ask

How to check if a file exists in C LINUX?

How To Check File Exists In C Linux? ‘ stat () Function to Look for if the file Exists in C Rather than reading statistics from a database, stat has returned 0, otherwise, -1. If a file is not present, the function is discarded. This has been returned so far. how do i check the presence of a file in linux? how do i check to see if a file exists?

How do I See File permissions in Linux?

The easiest way to view the file permissions in Linux for a specific file is using the “ls” command followed by the name of the file. For example, if we wanted to view the permissions for a file called “test.txt”, we would type ls -l test.txt at the command line. This will return a list of information about the file, including the permissions.

How to check if regular file exists in bash script?

Similarly using test command to check if regular file exists in bash or shell script in single line. 2. Bash/Shell: Check if file exists (is empty or not empty) To check if the file exists and if it is empty or if it has some content then we use " -s " attribute Check if file exists and empty or not empty using double brackets [ [..]]

How to check if a file exists or not in Python?

To check if the file exists and if it is empty or if it has some content then we use " -s " attribute Check if file exists and empty or not empty using double brackets [ [..]]


1 Answers

The only correct way to check if a file exists is to try to open it. The only correct way to check if a file is writable is to try to open it for writing. Anything else is a race condition. (Other API calls can tell you if the file existed a moment ago, but even if it did, it might not exist those 15 nanoseconds later, when you try to actually open it, so they're largely useless)

However, if you want to know if a file exists without opening it, simply use the boost::filesystem::exists function. But be aware of the gaping flaw in it. It doesn't tell you if the file exists, it tells you if the file existed.

So be careful how you use it. Don't assume that just because the function returned true, that the file will exist when you actually try to open it.

If you need to know "will I be able to open this file", then the only way to find out is to try to open it.

like image 176
jalf Avatar answered Oct 18 '22 14:10

jalf