1

I want to check if a file exists and tried to use the following function

#include <fstream>

bool DoesFileExist(const std::string& filename) {
    std::ifstream ifile(filename.c_str());
    return (bool)ifile;
    }

However, it does not seem to work properly, because instead of checking the existence a file is created! What's the problem here?

Note that I'm forced to use C++98 standard and cannot use #include <sys/stat.h> or #include <unistd.h> as suggested in the accepted answer here.

Ethunxxx
  • 1,229
  • 4
  • 16
  • 34
  • 1
    If possible, learn C++11; C+98 is really obsolete. And read documentation of [std::ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream) carefully. Post also some [MCVE](https://stackoverflow.com/help/mcve). Your shown code probably don't behave as you say – Basile Starynkevitch Sep 19 '17 at 05:54
  • 1
    Did [this answer](https://stackoverflow.com/a/6297560/4143855) not help? `std::fstream ifile(filename.c_str(), ios_base::out | ios_base::in);` – Tas Sep 19 '17 at 05:57
  • Not reproducible https://ideone.com/Z4c2EW – n. m. could be an AI Sep 19 '17 at 06:05
  • 1
    To what purpose do you want to do this? In general, I try to avoid "checking if a file exists" etc, because of the "Time Of Check To Time of Use" problems that this creates. – Mats Petersson Sep 19 '17 at 06:05
  • See my discussion on the subject here: https://stackoverflow.com/questions/17818099/how-to-check-if-a-file-exists-before-creating-a-new-file – Mats Petersson Sep 19 '17 at 06:07

1 Answers1

9

You can use either of these functions to see if a file exists

bool DoesFileExist (const std::string& name) {
    ifstream f(name.c_str());
    return f.good();
}

or

bool DoesFileExist (const std::string& name) {
    if (FILE *file = fopen(name.c_str(), "r")) {
        fclose(file);
        return true;
    } else {
        return false;
    }   
}

or

bool DoesFileExist (const std::string& name) {
    return ( access( name.c_str(), F_OK ) != -1 );
}

or

bool DoesFileExist (const std::string& name) {
  struct stat buffer;   
  return (stat (name.c_str(), &buffer) == 0); 
}
Sinapse
  • 786
  • 1
  • 6
  • 23
  • 2
    Good for using `fopen()`. Unfortunately, `std::ifstream` may validly _create_ a file. – Dúthomhas Sep 19 '17 at 05:58
  • 1
    About usage of fopen . File may exist, but you may not be able to read it. In this case fopen may not return a valid pointer... – Ivan P. Jan 25 '19 at 13:33