利用线程目录拷贝

#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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值