Possible Duplicate:
How can we check if a file Exists or not using Win32 program?
Which is the best method for checking for file existence:
Option1:
GetFileAttributes("C:\\MyFile.txt"); // from winbase.h if(0xffffffff == GetFileAttributes("C:\\MyFile.txt")) { //File not found }
Option2:
std::string fileName("C:\\MyFile.txt" ); ifstream fin( fileName.c_str() ); if( fin.fail() ) { //File not found }
Also if you think option 1 is the better method, can you tell me how to define 0xffffffff
as a constant (I don't want to use #define)
Thanks
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.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
Note that GetFileAttributes() may fail for other reasons than lack of existence (for example permissions issues). I would add a check on the error code for robustness:
GetFileAttributes("C:\\MyFile.txt"); // from winbase.h if(INVALID_FILE_ATTRIBUTES == GetFileAttributes("C:\\MyFile.txt") && GetLastError()==ERROR_FILE_NOT_FOUND) { //File not found }
There are two things to consider here:
Checking if the file exists via its attributes is potentially many orders of magnitude faster - If a file exists on a 'slow' file system - tape, network storage, cd etc then opening the file will involve an actual round trip to the files location. The files attributes on the other hand are queried and cached by the filesystem drivers when the directory is queried, so probing file attributes involves a once off directory enumeration cost - meaning far fewer round trips - which can be a significant saving if multiple "slow" files are being checked.
However, the files attributes merely indicate that the file existed at the time the call was made. The file can be deleted, or you might not haver permissions to access it. If you are about to try and open the file anyway, it would be better to dispense with the file attributes check and actually try and open the file.
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