需要做一个软件更新的功能,软件更新过程中需要考虑一些异常,其中关于固件备份(防止升级失败)的过程,不甘心用system((char *)cmd)的方式,采用文件打开读写关闭的方式实现。
/**
* @brief 复制文件夹
* @param sourcePath 源文件夹
* @param destPath 目的文件夹
*/
void copyfolder(std::string sourcePath, std::string destPath)
{
struct dirent *filename = NULL;
std::string path = sourcePath;
opendir(destPath.c_str());
if (sourcePath.back() != '/')
{
sourcePath += "/";
}
if (destPath.back() != '/')
{
destPath += "/";
}
DIR *dp = opendir(path.c_str());
if (dp == NULL)
return;
while (filename = readdir(dp))
{
std::string fileSourcePath = sourcePath;
std::string fileDestPath = destPath;
fileSourcePath += filename->d_name;
fileDestPath += filename->d_name;
if (is_dir(fileSourcePath.c_str()))
{
if (strncmp(filename->d_name, ".", 1) && strncmp(filename->d_name, "..", 2))
copyfolder(fileSourcePath, fileDestPath);
}
else
{
copyfile(fileSourcePath, fileDestPath);
}
}
}
/**
* @brief 复制文件
* @param sourcePath 源文件
* @param destPath 目的文件
*/
void copyfile(std::string sourcePath, std::string destPath)
{
int pIn, pOut;
char buff[FILE_CACHE] = {0};
if ((pIn = open(sourcePath.data(), O_RDONLY)) == -1)
return;
struct stat sourceStat;
stat(sourcePath.data(), &sourceStat);
int flag = destPath.find_last_of("/");
std::string destFile = destPath.substr(0, flag);
is_file_exist(destFile, true);
if (S_IXUSR & sourceStat.st_mode)
pOut = open(destPath.data(), O_CREAT | O_RDWR | O_TRUNC, 0775);
pOut = open(destPath.data(), O_CREAT | O_RDWR | O_TRUNC, 0444);
if (pOut == -1)
return;
int len = 0;
int temp_source_size = sourceStat.st_size;
int temp_cnt = 0;
while (temp_source_size > 0)
{
len = 0;
len = read(pIn, buff, FILE_CACHE);
write(pOut, buff, len);
temp_source_size -= len;
temp_cnt += len;
}
close(pOut);
close(pIn);
}