0

i'm acctually using the open function with option "std::ios::out | std::ios::app" to create file or append to it, but now i need to distinguish the case in which the file exists from the case in which the file doesn't exists. In fact, if the file doesn't exist, i have to create it and add to it an header (a string at the beginning), else i have to append content to the file.. How can i make this? i've read about the fstat function that returns -1 if errors occur. Buf if fstat returns -1, can i be sure the file doesn't exist?

Thanks

dang92
  • 31
  • 5
  • 1
    Possible duplicate of [Fastest way to check if a file exist using standard C++/C++11/C?](https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c) – Sean Mar 24 '18 at 10:32
  • have you tried to write out the code – Roushan Mar 24 '18 at 10:36
  • actually i don't need the fastest way but the simplest way! and in that discussion i read "fast seems to check.." – dang92 Mar 24 '18 at 10:38

2 Answers2

0

The simplest way to test if a file doesn't exist, is to open it with the ios::in flag. If this fails, the file doesn't exist.

MivVG
  • 679
  • 4
  • 16
  • is the fail bit set only if the file does not exist? because reading the specifications is not clear to me – dang92 Mar 24 '18 at 10:42
  • When trying to open using `ios::in` and the file doesn't exists, it just fails to open so you can check with `file.is_open()` or `file.good()` – MivVG Mar 24 '18 at 10:46
  • are there not cases in which the file exists but file.good() is false? reading about it, it is not much clear to me.. – dang92 Mar 24 '18 at 11:01
  • Then you should use `file.is_open()` – MivVG Mar 24 '18 at 11:02
  • but it's the same thing, no? if file.is_open() == false, am i sure that the file doesn't exist? is not possible that the file exists but some other errors occur?! – dang92 Mar 24 '18 at 11:04
  • Possibly, but then you can't open it anyway so that shouldn't make a big difference. Also, iostream errors don't really occur regularly. – MivVG Mar 24 '18 at 11:05
0

The easiest way is to manually check if the file exists then act upon the case.

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

int main() {
    std::string filename = "somefile.txt";

    std::fstream file;
    if(!exists_file(filename)) {
        file.open(filename, std::ios::out);
        write_headers(file);
    }
    else {
        file.open(filename, std::ios::out | std::ios::app);
    }

    write_something(file);
    file.close();

    return 0;
}
phuctm97
  • 136
  • 1
  • 9