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:
Does this code have any pitfalls? (maybe an OS where it cannot be compiled)
Is it possible to do it in a truly portable way using only C/C++ standard library?
How to improve it? Looking for canonical example.
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.
The isDir() function is used to check a given file is a directory or not.
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 .
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.
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