Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 302
cweston Avatar asked Nov 30 '10 17:11

cweston


People also ask

How do you check if a file already exists C++?

A simple function: bool exist(string PATH) { ifstream fin; fin. open(PATH. c_str()); return bool(fin); } Now, checking : if(exist("a. txt")) { //fstream file; //file.

When using an ofstream what happens when the output file name already exists?

If the file already exists, the old version is deleted. Appending records to an existing file or creating one if it doesn't exist. ofstream ofile("FILENAME", ios::app); Opening two files, one at a time, on the same stream.

Does ofstream overwrite?

Using ofstream with the "current file" name as parameter for the constructor will overwrite it.

Does ofstream open a file?

std::ofstream::open. Opens the file identified by argument filename , associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode. If the stream is already associated with a file (i.e., it is already open), calling this function fails.


4 Answers

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

#include <sys/stat.h>
// 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.

like image 70
Rico Avatar answered Oct 13 '22 20:10

Rico


bool fileExists(const char *fileName)
{
    ifstream infile(fileName);
    return infile.good();
}

This method is so far the shortest and most portable one. If the usage is not very sophisticated, this is one I would go for. If you also want to prompt a warning, I would do that in the main.

like image 37
return 0 Avatar answered Oct 13 '22 18:10

return 0


fstream file;
file.open("my_file.txt", ios_base::out | ios_base::in);  // will not create file
if (file.is_open())
{
    cout << "Warning, file already exists, proceed?";
    if (no)
    { 
        file.close();
        // throw something
    }
}
else
{
    file.clear();
    file.open("my_file.txt", ios_base::out);  // will create if necessary
}

// do stuff with file

Note that in case of an existing file, this will open it in random-access mode. If you prefer, you can close it and reopen it in append mode or truncate mode.

like image 9
HighCommander4 Avatar answered Oct 13 '22 18:10

HighCommander4


With std::filesystem::exists of C++17:

#include <filesystem> // C++17
#include <iostream>
namespace fs = std::filesystem;

int main()
{
    fs::path filePath("path/to/my/file.ext");
    std::error_code ec; // For using the noexcept overload.
    if (!fs::exists(filePath, ec) && !ec)
    {
        // Save to file, e.g. with std::ofstream file(filePath);
    }
    else
    {
        if (ec)
        {
            std::cerr << ec.message(); // Replace with your error handling.
        }
        else
        {
            std::cout << "File " << filePath << " does already exist.";
            // Handle overwrite case.
        }
    }
}

See also std::error_code.

In case you want to check if the path you are writing to is actually a regular file, use std::filesystem::is_regular_file.

like image 5
Roi Danton Avatar answered Oct 13 '22 19:10

Roi Danton