I'm working on an app that writes/copies files and thought of updating the code to C++17's filesystem.
I'm on Windows 11 using g++ v12.2
with MSYS2 MinGW 64-bit.
Below is a summary of my app's behavior.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::create_directories("sandbox");
std::ofstream ofs;
ofs.open ("sandbox/file1.txt", std::ofstream::out | std::ofstream::app);
ofs << "hello";
ofs.close();
std::cout << "test copy file" << std::endl;
fs::copy("sandbox/file1.txt", "sandbox/file2.txt", fs::copy_options::overwrite_existing); // copy file
static_cast<void>(std::system("tree"));
//sometime later, file is updated
ofs.open ("sandbox/file1.txt", std::ofstream::out | std::ofstream::app);
ofs << "world";
ofs.close();
//sometime later, need to update file2 via copy
std::cout << "test copy file again" << std::endl;
fs::copy("sandbox/file1.txt", "sandbox/file2.txt", fs::copy_options::overwrite_existing); // copy file
fs::remove_all("sandbox");
}
Above code was compiled with:
g++ -c -std=gnu++17 testcopy.cpp -o testcopy.o
g++ ./testcopy.o -o testcopy.exe
Then, you'll get this:
./testcopy.exe
test copy file
Folder PATH listing for volume Acer
Volume serial number is 38B3-48F3
C:.
└───sandbox
test copy file again
terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
what(): filesystem error: cannot copy: File exists [sandbox/file1.txt] [sandbox/file2.txt]
I wonder if I have to release
, free
, or close
file2.txt after first copy but I don't know how.
Or, possibly, copy_options is not supported by GCC on Windows, to which I'm okay defer porting my code to C++17.
I was expecting copy_options::overwrite_existing
will handle the File exists
problem. I've also used copy_options::update_existing
to no avail.