#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#define MAX_PATH 1024
void dirwalk(char *srcdir,char *destdir,void (*fcn)(char *,char *));
void fsize(char *srcname,char *destname);
int main(int argc,char *argv[])
{
if(access(argv[2],F_OK) == -1)
{
mkdir(argv[2],0755);//如果目标目录不存在的话,就创建
}
dirwalk(argv[1],argv[2],fsize);
return 0;
}
void copy(char *srcname,char *destname)
{
char buf[1024] = {0};
int n,fd1,fd2;
fd1 = open(srcname,O_RDONLY);
fd2 = open(destname,O_RDWR | O_TRUNC | O_CREAT,0644);
while(n = read(fd1,buf,sizeof(buf)))
{
write(fd2,buf,n);
}
close(fd1);
close(fd2);
}
void fsize(char *srcname,char *destname)
{
struct stat stbuf;
if(lstat(srcname,&stbuf) == -1)
{
fprintf(stderr,"fsize:can not access %s\n",srcname);
return;
}
if((stbuf.st_mode & S_IFMT) == S_IFDIR)//遇到目录
{
mkdir(destname,stbuf.st_mode);//创建目录 0755是比较粗糙的做法
dirwalk(srcname,destname,fsize);
}
//printf("%8ld %s\n",stbuf.st_size,name);
else
copy(srcname,destname);
}
void dirwalk(char *srcdir,char *destdir,void (*fcn)(char *,char *))
{
char srcname[MAX_PATH] = {0};
char destname[MAX_PATH] = {0};
struct dirent *dp = NULL;
DIR *dfd = NULL;
dfd = opendir(srcdir);
if(!dfd)
{
fprintf(stderr,"dirwalk: can not open %s\n",srcdir);
return;
}
while((dp = readdir(dfd)) != NULL)
{
if(!strcmp(dp->d_name,".") || !strcmp(dp->d_name,".."))
continue;
if(strlen(srcdir) + strlen(dp->d_name) + 2 > sizeof(srcname))
fprintf(stderr,"dirwalk:name %s %s too long\n",srcdir,dp->d_name);
else
{
sprintf(srcname,"%s/%s",srcdir,dp->d_name);
sprintf(destname,"%s/%s",destdir,dp->d_name);
(*fcn)(srcname,destname);
}
}
}
cp命令的简单实现(可拷贝目录)
最新推荐文章于 2023-11-23 14:26:33 发布