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?
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.
Use ifile. open(): ifile. open() is mainly used to check if a file exists in the specific directory 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).
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.
Use boost::filesystem:
#include <boost/filesystem.hpp> if ( !boost::filesystem::exists( "myfile.txt" ) ) { std::cout << "Can't find my file!" << std::endl; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With