Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if file exists in C++ in a portable way?

Currently I use this code to check if file exists on Windows and POSIX-compatible OSes (Linux, Android, MacOS, iOS, BlackBerry 10):

bool FileExist( const std::string& Name )
{
#ifdef OS_WINDOWS
    struct _stat buf;
    int Result = _stat( Name.c_str(), &buf );
#else
    struct stat buf;
    int Result = stat( Name.c_str(), &buf );
#endif
    return Result == 0;
}

Questions:

  1. Does this code have any pitfalls? (maybe an OS where it cannot be compiled)

  2. Is it possible to do it in a truly portable way using only C/C++ standard library?

  3. How to improve it? Looking for canonical example.

like image 344
Sergey K. Avatar asked Aug 19 '13 18:08

Sergey K.


People also ask

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

stat() Function to Check if a File Exists in C We read the file's attributes using the stat() function instead of reading data from a file. This function will return 0 if the operation is successful; otherwise, it will return -1 , if the file does not exist.

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

The isDir() function is used to check a given file is a directory or not.

How do I make sure 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 .


1 Answers

I perosnally like to just try to open the file:

bool FileExist( const std::string& Name )
{
     std::ifstream f(name.c_str());  // New enough C++ library will accept just name
     return f.is_open();
}

should work on anything that has files [not required by the C++ standard] and since it's using C++ std::string, I don't see why std::ifstream should be a problem.

like image 117
Mats Petersson Avatar answered Oct 26 '22 11:10

Mats Petersson