用线程的方式实现一个目录的拷贝(只考虑目录和普通文件)
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX 1024
struct ctwo{
char *old;
char *new;
};
void* thread(void* arg)
{
struct ctwo * p = (struct ctwo *)arg;
int fp1 = open(p -> old,O_RDONLY);
if(fp1 == -1)
{
perror("open p1 error\n");
goto cp_return;
}
int fp2 = open(p-> new,O_WRONLY | O_CREAT | O_TRUNC,0777);
if(fp2 == -1)
{
perror("open p2 error\n");
goto cp_return;
}
int ret;
char buf[MAX]={0};
while(1)
{
ret = read(fp1,buf,MAX);
if(ret == 0)
{
break;
}
else if(ret >0)
{
int ret_write = write(fp2,buf,ret);
if(ret_write == -1)
{
perror("write error\n");
}
}
else{
perror("read error\n");
}
}
cp_return:
free(arg);
close(fp1);
close(fp2);
return NULL;
}
int cp(char *p,char *pre)
{
int len = strlen(p)-1;
while(*(p+len) != '/')
{
len--;
}
char *p1=p+len+1;
char filename[MAX]={0};
sprintf(filename,"%s/%s",pre,p1);
mkdir(filename,0777);
pre = filename;
DIR *dir = opendir(p);
if(dir == NULL)
{
perror("opendir error\n");
}
struct dirent *fp = NULL;
while(fp = readdir(dir))
{
if(strcmp(fp->d_name,".")==0 || strcmp(fp->d_name,"..")==0)
{
continue;
}
char file_old[MAX]={0};
sprintf(file_old,"%s/%s",p,fp->d_name);
char file_new[MAX]={0};
sprintf(file_new,"%s/%s",pre,fp->d_name);
struct stat st;
lstat(file_old,&st);
if(S_ISREG(st.st_mode)||S_ISLNK(st.st_mode))
{
struct ctwo *t =malloc(sizeof(*t));
t -> old = file_old;
t -> new = file_new;
pthread_t th;
pthread_create(&th,NULL,thread,(void*)t);
pthread_join(th,NULL);
}
else if(S_ISDIR(st.st_mode))
{
cp(file_old,pre);
}
}
closedir(dir);
return -1;
}
int main(int argc,char*argv[])
{
if(argc > 3)
{
printf("input error\n");
return -1;
}
char *p;
char *pre;
p = argv[1];
pre = argv[2];
cp(p,pre);
return 0;
}
***注意:1、进程文件传参的转换
2、目录文件创建的用 mkdir***