Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the best way to check if a file exists in C++? (cross platform)

Tags:

c++

file

file-io

I have read the answers for What's the best way to check if a file exists in C? (cross platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all.

Both stat and access are pretty much ungoogleable. What should I #include to use these?

like image 524
c0m4 Avatar asked Nov 06 '08 09:11

c0m4


People also ask

How do you check if a file already exists in C?

access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.

How do you check if a file is present in a directory in C++?

Use ifile. open(): ifile. open() is mainly used to check if a file exists in the specific directory or not.

Which of the following is used to check whether file exists or not?

While checking if a file exists, the most commonly used file operators are -e and -f. The '-e' option is used to check whether a file exists regardless of the type, while the '-f' option is used to return true value only if the file is a regular file (not a directory or a device).

How do you check if a file exists in C++ Windows?

The FileExists Method (System::SysUtils::FileExists) is a SysUtils Method in C++ Builder that checks whether a specified file exists. FileExists returns True if the file specified by FileName exists. If the file does not exist, FileExists returns False.


2 Answers

Use boost::filesystem:

#include <boost/filesystem.hpp>  if ( !boost::filesystem::exists( "myfile.txt" ) ) {   std::cout << "Can't find my file!" << std::endl; } 
like image 99
Andreas Magnusson Avatar answered Oct 06 '22 11:10

Andreas Magnusson


Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.

It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.

Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html

like image 22
rlerallut Avatar answered Oct 06 '22 10:10

rlerallut