#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
//拷贝缓冲区结构体
struct file
{
char old_file[1024];
char new_file[1024];
};
//线程拷贝函数
void *cp_task(void *arg)
{
printf("%ld线程启动\n",pthread_self());
struct file *f = arg;
//开始拷贝
//打开源文件
FILE *fp = fopen(f->old_file,"r");
if(fp == NULL)
{
perror("");
return NULL;
}
//新建目标文件
FILE *fp1 = fopen(f->new_file,"w+");
if(fp1 == NULL)
{
perror("");
return NULL;
}
//进行拷贝
while (1)
{
if(feof(fp))
{
printf("f->old_file:%s,f->new_file:%s\n",f->old_file,f->new_file);
break;//拷贝完毕
}
fputc(fgetc(fp),fp1);
}
//释放堆空间
free(f);
//关闭所有文件
fclose(fp);
fclose(fp1);
}
int main(int argc,char *argv[])
{
if(argc != 3)
{
printf("请输入 ./main 目录1 目录2\n");
return 1;
}
//打开参数1目录
DIR *dp=opendir(argv[1]);
if(dp==NULL)
{
perror("打开目录失败\n");
return -1;
}
//创建新的目录
mkdir(argv[2],0777);
//读取目录中的数据
while (1)
{
struct dirent *msg=readdir(dp);
if(msg == NULL)
{
printf("读取完毕\n");
break;
}
//判断是否为普通文件
if(msg->d_type == DT_REG)
{
//新建文件结构体
struct file *f = malloc(sizeof(struct file));
sprintf(f->old_file,"%s/%s",argv[1],msg->d_name);
sprintf(f->new_file,"%s/%s",argv[2],msg->d_name);
//开启线程拷贝文件
pthread_t tid;
pthread_create(&tid,NULL,cp_task,f);
}
}
pause();
}