2024年9月29日14:20:05更新
修改 int CopyFile(std::string sourcePath,std::string destPath)
函数,fopen(destPath)
失败时,return 1
之前,需要使用fclose()
方法关闭源路径文件流。
一、 前言
本文是在该文“Linux C++实现拷贝文件夹”的基础上做了一些修改和优化:
- 修改了CopyFile(std::string sourcePath,std::string destPath)函数返回值不匹配的问题;
- 原文代码只支持拷贝文件夹,增加拷贝文件功能.
二、代码测试环境
编程语言 | 操作系统 | 系统架构 | 控制器 |
---|---|---|---|
C++ 11 | Ubuntu 18.04 LTS | arm64 | LCFC EA-B310 |
三、代码实现
copy.cpp
#include<stdlib.h>
#include<dirent.h>
#include<string.h>
#include<stdio.h>
#include<sys/stat.h>
#include<iostream>
#define BUFFER_LENGTH 8192
// 判断传入的路径是否是目录(不是目录就是文件),目录返回1,文件返回0
int IsDir(std::string path)
{
if(path.empty())
{
return 0;
}
struct stat st;
if(0 != stat(path.c_str(),&st))
{
return 0;
}
if(S_ISDIR(st.st_mode))
{
return 1;
}
else
{
return 0;
}
}
void AddSlash(std::string &sourcePath,std::string &destPath)
{
if((IsDir(sourcePath)) && (sourcePath.back() != '/'))
<