Daily bit(e) of C++ | std::filesystem: file manipulation

Šimon Tóth
1 min readAug 31, 2023

--

Daily bit(e) of C++ #242, File manipulation using the std::filesystem library.

Besides filesystem exploration, the std::filesystem offers the typical file manipulation operations.

Each operation offers two variants, one throwing one that returns the potential error as an outparameter.

The following example relies on throwing versions of operations to minimize error handling.

#include <filesystem>
#include <fstream>
#include <stdexcept>

std::filesystem::path file = "current_file";
{
std::ofstream f(weakly_canonical(file));
f << "Current content\n";
}

// Create a backup folder if it doesn't exist
std::filesystem::path backup_folder = "./backup";
if (!exists(backup_folder)) create_directory(backup_folder);

// Check if there is sufficient space
if (space(backup_folder).available < file_size(file))
throw std::runtime_error("Not enough space for backup.");

// Construct a filename with a timestamp
std::filesystem::path backup_file = backup_folder / file.filename();
{
using namespace std::chrono;
auto cnt =
duration_cast<seconds>(system_clock::now().time_since_epoch())
.count();
backup_file += std::to_string(cnt);
}
// Create a backup
copy(file, backup_file);

// Create or update the symlink to the latest backup
std::filesystem::path symlink = file.parent_path() / "current_backup";
if (exists(symlink)) remove(symlink);
create_symlink(backup_file, symlink);

/* Example result:
"./current_backup" ("./backup/current_file1662980474")
"./current_file"
"./backup"
"./backup/current_file1662980474"
*/

Open the example in Compiler Explorer.

--

--

Šimon Tóth

20 years worth of Software Engineering experience distilled into easily digestible articles.