linux下C语言实现cp命令复制文件与文件夹

您所在的位置:网站首页 cp命令文件夹 linux下C语言实现cp命令复制文件与文件夹

linux下C语言实现cp命令复制文件与文件夹

2024-06-06 05:38| 来源: 网络整理| 查看: 265

版权声明:本文为博主原创文章,未经博主允许,欢迎随意转载,标好作者+原文地址就可以了!感谢欣赏!觉得好请回个贴! 

https://blog.csdn.net/jackcsdnfghdtrjy/article/details/86551475

1、使用标准I/O实现文件复制;

2、使用目录检索寻找文件夹,并递归复制文件夹。

代码:

#include #include #include #include #include #include int is_dir(char* path);//判断是否是目录 是返回1 否则返回0 int copy_file(char* srcPath,char *destPath);//复制文件 成功返回0 否则返回 -1 int copy_folder(char* srcPath,char *destPath);//复制文件夹 成功返回0 否则返回 -1 int main(int argc,char *argv[]) //argv[1] 源文件 argv[2] 目标文件 { if(argc != 3) { printf("Usage srcfile destfile\n"); return -1; } char* srcPath=argv[1]; char* destPath=argv[2]; if(is_dir(srcPath)) //文件夹的拷贝 { copy_folder(srcPath,destPath); } else { if(access(destPath,F_OK) == 0) //保证destPath是未存在的目录 { printf("目标文件已存在\n"); return -1; } copy_file(srcPath,destPath);//文件进行拷贝 } return 0; } //判断是否是目录 是返回1 否则返回0 int is_dir(char* path) { struct stat st; stat(path,&st); if(S_ISDIR(st.st_mode)) return 1; else return 0; } //复制文件 成功返回0 否则返回 -1 int copy_file(char* srcPath,char *destPath) { char Buf[1024] = {0}; int count_read = 0; long fp_src_ltell = 0,fp_src_atell = 0; FILE* fp_src = fopen(srcPath,"r");//只读方式打开 FILE* fp_dst = fopen(destPath,"w");//只写方式打开 if(fp_dst ==NULL || fp_src == NULL) { printf("文件打开有问题\n"); return -1; } while(1) { memset(Buf,0,sizeof(Buf)); fp_src_ltell = ftell(fp_src); //上一次文件指针位置 count_read = fread(Buf,sizeof(Buf),1,fp_src); fp_src_atell = ftell(fp_src); //当前文件指针位置 if(count_read2) //去除隐藏文件 . .. { bzero(newsrcPath,sizeof(newsrcPath)); //清空 bzero(newdestPath,sizeof(newdestPath)); sprintf(newsrcPath,"%s/%s",srcPath,srcDirent->d_name);//保存新的文件路径 sprintf(newdestPath,"%s/%s",destPath,srcDirent->d_name); if(srcDirent->d_type == DT_DIR) //文件夹的拷贝 copy_folder(newsrcPath,newdestPath); else //普通文件 copy_file(newsrcPath,newdestPath); } } return 0; }

运行:

复制rr文件夹,rr文件夹如下图:

运行过程与结果:



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3