if i use boostfilesystem how can i prevent overwriting of previous password files?

Boost.Filesystem offers an operation called exists, along with other operations for querying status of a file. You could generate the file name using a loop like below:

fs::path generate_filename(fs::path const& dir)
{
    fs::path path = dir / "password.txt";
    unsigned int counter = 1u;
    while (true)
    {
        if (!fs::exists(path))
            break;

        ++counter;
        if (counter == 0u)
            throw std::runtime_error("Failed to generate a unique file name");

        path = dir / std::string("password")
            .append(std::to_string(counter)).append(".txt");
    }

    return path;
}

However, note that the code is racy, because the file can be created between the call to exists and opening the file for writing. The solution is to test if the file exists while opening the file.

As of C++20 standard C++ file streams do not allow to test if the file exists while opening the file for writing, so you will have to use a different file API. Starting with C11, fopen allows to specify “x” in the file open mode to indicate that the function must fail if the file exists. You have to consult with your compiler or standard C library documentation to see if it supports this new addition.

Alternatively, you could use low level filesystem API, such as open call with O_CREAT and O_EXCL flags on POSIX systems or CreateFile with CREATE_NEW flag on Windows.


A couple of unrelated notes.

  1. You don’t need to static_cast<std::string>(array) to output a C-style string to a stream. Directly outputting a character array will work – the characters from the array will be written to the stream up until the first null character (terminator). By casting you just unnecessarily allocate dynamic memory and copy the string before outputting.

  2. Avoid accepting potentially large objects, like containers, strings or paths, in function arguments by value, unless required by the function body. Your fs::path dir argument could be better accepted as a const reference (fs::path const& dir), which would potentially avoid having to copy the path at the point of calling savePassword.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top