std::ofstream, check if file exists before writing

后端 未结 6 1740
予麋鹿
予麋鹿 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 14:10

    This is one of my favorite tuck-away functions I keep on hand for multiple uses.

    #include 
    // Function: fileExists
    /**
        Check if a file exists
    @param[in] filename - the name of the file to check
    
    @return    true if the file exists, else false
    
    */
    bool fileExists(const std::string& filename)
    {
        struct stat buf;
        if (stat(filename.c_str(), &buf) != -1)
        {
            return true;
        }
        return false;
    }
    

    I find this much more tasteful than trying to open a file if you have no immediate intentions of using it for I/O.

提交回复
热议问题