What’s the best way to check if a file exists in C++? (cross platform)

C++FileFile Io

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

Solution 2 - C++

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

Solution 3 - C++

I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:

ifstream file(argv[1]);
if (!file)
{
    // Can't open file
}

It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.

Solution 4 - C++

Use stat(), if it is cross-platform enough for your needs. It is not C++ standard though, but POSIX.

On MS Windows there is _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64.

Solution 5 - C++

If your compiler supports C++17 you don't need boost, you can simply use std::filesystem::exists

#include <iostream> // only for std::cout
#include <filesystem>

if (!std::filesystem::exists("myfile.txt"))
{
    std::cout << "File not found!" << std::endl;
}

Solution 6 - C++

How about access?

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}

Solution 7 - C++

Another possibility consists in using the good() function in the stream:

#include <fstream>     
bool checkExistence(const char* filename)
{
     ifstream Infield(filename);
     return Infield.good();
}

Solution 8 - C++

I would reconsider trying to find out if a file exists. Instead, you should try to open it (in Standard C or C++) in the same mode you intend to use it. What use is knowing that the file exists if, say, it isn't writable when you need to use it?

Solution 9 - C++

NO [tag:boost] REQUIRED, which would be an overkill.


Use stat() (not cross platform though as mentioned by pavon), like this:

#include <sys/stat.h>
#include <iostream>

// true if file exists
bool fileExists(const std::string& file) {
    struct stat buf;
    return (stat(file.c_str(), &buf) == 0);
}

int main() {
    if(!fileExists("test.txt")) {
        std::cerr << "test.txt doesn't exist, exiting...\n";
        return -1;
    }
    return 0;
}

Output:

C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt
ls: test.txt: No such file or directory
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
test.txt doesn't exist, exiting...

Another version (and that) can be found here.

Solution 10 - C++

If you are already using the input file stream class (ifstream), you could use its function fail().

Example:

ifstream myFile;

myFile.open("file.txt");

// Check for errors
if (myFile.fail()) {
    cerr << "Error: File could not be found";
    exit(1);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionc0m4View Question on Stackoverflow
Solution 1 - C++Andreas MagnussonView Answer on Stackoverflow
Solution 2 - C++rlerallutView Answer on Stackoverflow
Solution 3 - C++MattyTView Answer on Stackoverflow
Solution 4 - C++activout.seView Answer on Stackoverflow
Solution 5 - C++AlbertMView Answer on Stackoverflow
Solution 6 - C++RobView Answer on Stackoverflow
Solution 7 - C++SamerView Answer on Stackoverflow
Solution 8 - C++fizzerView Answer on Stackoverflow
Solution 9 - C++gsamarasView Answer on Stackoverflow
Solution 10 - C++Reza SaadatiView Answer on Stackoverflow