C++ File Operation
File operation with C++ can be a headache. I first tried with Windows API’s CopyFile()
, but it took a lot of trial and error for me to figure out that under Visual Studio the text encoding has to be changed from UNICODE to Not Set. Then I found the following solution from StackOverflow, which is much simpler.
#include <exception>
#include <experimental/filesystem> // C++-standard filesystem header file in VS15, VS17.
#include <iostream>
namespace fs = std::experimental::filesystem; // experimental for VS15, VS17.
/*! Copies all contents of path/to/source/directory to path/to/target/directory.
*/
int main()
{
fs::path source = "path/to/source/directory";
fs::path targetParent = "path/to/target";
auto target = targetParent / source.filename(); // source.filename() returns "directory".
try // If you want to avoid exception handling then use the error code overload of the following functions.
{
fs::create_directories(target); // Recursively create target directory if not existing.
fs::copy(source, target, fs::copy_options::recursive);
}
catch (std::exception& e) // Not using fs::filesystem_error since std::bad_alloc can throw too.
{
std::cout << e.what();
}
}
The code I have adapted is as follows
char iFilePath[500];
char qFilePath[500];
sprintf_s(iFilePath, "%s%s/1.rlf", folderPath, iPhoneFolderData.cFileName);
sprintf_s(qFilePath, "%s%s/2.rlf", folderPath, iPhoneFolderData.cFileName);
//CopyFile(LPCSTR(ifilePath), LPCSTR(iFilePath), false);
//CopyFile(LPCSTR(qfilePath), LPCSTR(qFilePath), false);
fs::path source = ifilePath;
fs::path target = iFilePath;
fs::copy(source, target, fs::copy_options::overwrite_existing);
source = qfilePath;
target = qFilePath;
fs::copy(source, target, fs::copy_options::overwrite_existing);