I'm working with files in my project using std::filesystem (fs) library. All paths I store as fs::path variables. My code is:
int main(){
std::filesystem::path root_dir = "/home/xyz/study/misis2023f-22-3-kovaleva-m-a/prj.cw/test_dir";
std::filesystem::path from_path = "/home/xyz/study/misis2023f-22-3-kovaleva-m-a/prj.cw/test_dir/misis2023_kovaleva_m_a/make.cpp";
std::cout << std::filesystem::exists(from_path) << '\n';
std::filesystem::copy_file(from_path, root_dir, std::filesystem::copy_options::update_existing);
}
I face the problem when I call fs::copy function, Invalid argument. But as you see, other functions (ex. fs::exists) work fine with those variables:
terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error' what(): filesystem error: cannot copy file: Invalid argument [/home/xyz/study/misis2023f-22-3-kovaleva-m-a/prj.cw/test_dir/misis2023_kovaleva_m_a/make.cpp] [/home/xyz/study/misis2023f-22-3-kovaleva-m-a/prj.cw/test_dir]
function signature: (from cpp-reference)
void copy( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options );
How can I fix this problem with argument?
I use cmake 3.22.1, ubuntu 22.04
I tried to pass argument as a string:
std::filesystem::copy_file("/home/xyz/study/misis2023f-22-3-kovaleva-m-a/prj.cw/test_dir/misis2023_kovaleva_m_a/make.cpp", root_dir, std::filesystem::copy_options::update_existing);
I tried to pass shorter argument:
std::filesystem::path from_path = "/home/xyz/study/test_copy.txt";
std::filesystem::copy_file(from_path, root_dir, std::filesystem::copy_options::update_existing);
I also tried to pass argument without extension:
std::filesystem::path from_path = "/home/xyz/study/what";
std::filesystem::copy_options::update_existing);
But results is the same: Invalid argument
I also tried to check file status:
std::filesystem::file_status from_path_status = std::filesystem::status(from_path);
Output is:
_M_type: std::filesystem:;file_type::regular
_M_perms: 436
You are trying to copy a file to a directory without specifying a target file name.
std::filesystem::copy_file()expects two file paths as it merely copies one file to another file. It cannot copy a file to a directory, like you are trying to do. Since you are passing it a directory path, it fails with the error.You need to either
specify a target file name for
std::filesystem::copy_file().use
std::filesystem::copy()instead.