I am looking for a simple example on how to copy a file from one directory to another in C. The program should only use cross platform functions that are native to C.
I made some changes to @te7 answer to copy just one file from one folder to another on MAC. I tried to modify his code to just copy one file but it was partially writing file to destination. So I use different code for file read/write
void copyFile(string srcDirPath, string destDirPath, string fileName)
{
string command = "mkdir -p " + destDirPath;
cerr << endl << "Command = " << command.c_str() << endl << endl;
system(command.c_str());
DIR* pnWriteDir = NULL; /*DIR Pointer to open Dir*/
pnWriteDir = opendir(destDirPath.c_str());
if (!pnWriteDir)
cerr << endl << "ERROR! Write Directory can not be open" << endl;
DIR* pnReadDir = NULL; /*DIR Pointer to open Dir*/
pnReadDir = opendir(srcDirPath.c_str());
if (!pnReadDir || !pnWriteDir)
cerr << endl <<"ERROR! Read or Write Directory can not be open" << endl << endl;
else
{
string srcFilePath = srcDirPath + fileName;
const char * strSrcFileName = srcFilePath.c_str();
fstream in, out;
in.open(strSrcFileName, fstream::in|fstream::binary);
if (in.is_open()) {
cerr << endl << "Now reading file " << strSrcFileName << endl;
string destFilePath = destDirPath + fileName;
const char * strDestFileName = destFilePath.c_str();
out.open(strDestFileName, fstream::out);
char tmp;
while(in.read(&tmp, 1))
{
out.write(&tmp, 1);
}
out.close();
in.close();
}
else
cerr << endl << "ERROR! File Could not be open for reading" << endl;
}
closedir(pnReadDir);
closedir(pnWriteDir);
}