c++streamstdfstreamofstream

std::ofstream, check if file exists before writing


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 before writing to it, so that I can prompt a warning to the user.

I am using an std::ofstream and I am not looking for a Boost solution.


Solution

  • File Exists Function

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

      #include <sys/stat.h>
    
      /**
        * File Exist Function
        *
        * @desc Check if a file exists
        *
        * @param filename - the name of the file to check
        *
        * @return 'true' if it exist, otherwise returns false.
        * */
        bool fileExists(const std::string& filename){
          struct stat buf;
    
          if (stat(filename.c_str(), &buf) != -1){ return true; }
    
          return false;
        }
    
    

    I find this solution to be much more tasteful than trying to open a file when you don't intend to stream in or out of it.