用c实现不用命令实现整个文件目录复制:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
int cpy(char *pathname,char *pathname2)
{
int o_fd,o_fd1;
o_fd=open(pathname,O_RDWR);//原目录
o_fd1=open(pathname2,O_RDWR|O_CREAT);//复制目标
if (o_fd==-1||o_fd1==-1)
{
printf("打开失败1\n");
}
char buf[10]={0};
int n,u=0;
while(1)
{
n=read(o_fd,buf,sizeof(buf)); //读写
write(o_fd1,buf,sizeof(buf));
if(n==0)//判断是否读完
{
break;
}
u+=10;
}
close(o_fd);
close(o_fd1);
return 0;
}
void dir_func(char *pathname,char *pathname2);
int main(int argc, char const *argv[])
{
char a[10],b[10];
sprintf(a,"%s",argv[1]);
sprintf(b,"%s",argv[2]);
mkdir(b,0777);
dir_func(a,b);
printf("复制成功");
return 0;
}
void dir_func(char *pathname,char *pathname2)
{
//打开目录
DIR *dir=opendir(pathname);
//定义目录项结构体指针
struct dirent *buf=NULL;
char s[20],s1[20];
while(1)
{
//读取目录指针到结构体里面去
buf=readdir(dir);
if (buf==NULL)
{
break;
}
if (buf->d_type==8) //普通文件
{
sprintf(s,"%s/%s",pathname,buf->d_name );
sprintf(s1,"%s/%s",pathname2,buf->d_name);
cpy(s,s1);
}
else if (buf->d_type==4)//判断是不是目录
{
if (buf->d_name[0]=='.')
{
continue;
}
sprintf(s,"%s/%s",pathname,buf->d_name );
sprintf(s1,"%s/%s",pathname2,buf->d_name );
mkdir(s1,0777);
dir_func(s,s1);
}
}
}