Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Which is the best method of checking for file existence on windows platform [duplicate]

Tags:

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

like image 730
Robben_Ford_Fan_boy Avatar asked Dec 09 '10 23:12

Robben_Ford_Fan_boy


People also ask

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

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 I check to see if a file exists?

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 .


2 Answers

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 } 
like image 65
zdan Avatar answered Sep 29 '22 10:09

zdan


There are two things to consider here:

  1. 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.

  2. 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.

like image 26
Chris Becke Avatar answered Sep 29 '22 10:09

Chris Becke