std::ofstream, check if file exists before writing

后端 未结 6 1745
予麋鹿
予麋鹿 2020-12-02 13:18

I am implementing file saving functionality within a Qt application using C++.

I am looking for a way to check to see if the selected file already exists be

6条回答
  •  庸人自扰
    2020-12-02 13:45

    One of the way would be to do stat() and check on errno.
    A sample code would look look this:

    #include 
    using namespace std;
    // some lines of code...
    
    int fileExist(const string &filePath) {
        struct stat statBuff;
        if (stat(filePath.c_str(), &statBuff) < 0) {
            if (errno == ENOENT) return -ENOENT;
        }
        else
            // do stuff with file
    }
    

    This works irrespective of the stream. If you still prefer to check using ofstream just check using is_open().
    Example:

    ofstream fp.open("", ofstream::out);
    if (!fp.is_open()) 
        return false;
    else 
        // do stuff with file
    

    Hope this helps. Thanks!

提交回复
热议问题