简体   繁体   中英

create file with header or append c++

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

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM