#include <myhead.h>
int getlen(const char *file1, const char *file2)
{
FILE *fp1 = NULL;
FILE *fp2 = NULL;
if((fp1 = fopen(file1, "r")) == NULL)
{
perror("file1 fopen error");
return -1;
}
if((fp2 = fopen(file2, "w+")) == NULL)
{
perror("file2 fopen error");
return -1;
}
fseek(fp1, 0, SEEK_END);
int len = ftell(fp1);
fclose(fp1);
fclose(fp2);
return len;
}
void copy_file(const char *file1, const char *file2, int stat, int len)
{
FILE *fp1 = NULL;
FILE *fp2 = NULL;
if((fp1 = fopen(file1, "r")) == NULL)
{
perror("file fopen error");
return ;
}
if((fp2 = fopen(file2, "w")) == NULL)
{
perror("file2 fopen error");
return ;
}
fseek(fp1, stat, SEEK_SET);
fseek(fp2, stat, SEEK_SET);
char buf[128] = "";
while(1)
{
fread(buf, sizeof(char), 1, fp1);
int a = ftell(fp1);
if(a > len)
{
break;
}
fwrite(buf, sizeof(char), 1, fp2);
fflush(fp2);
}
fclose(fp2);
fclose(fp1);
printf("拷贝成功\n");
return ;
}
typedef struct
{
char *src_file;
char *dst_file;
int end;
int mid;
}Data;
void *task1(void *arg)
{
sleep(5);
Data data = (struct Data*)arg;
copy_file(data.src_file, data.dst_file, data.mid, data.end);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//向文件写入内容
FILE *fp = NULL;
if((fp = fopen("./file1", "w")) == NULL)
{
perror("fopen error");
return -1;
}
char buf[128] = "";
while(1)
{
fscanf(stdin, "%s", buf);
if(strcmp(buf, "nihao") == 0)
{
break;
}
fprintf(fp, "%s\n", buf);
}
//关闭文件刷新
fclose(fp);
char src_file[] = "./file1";
char dst_file[] = "./file2";
//求源文件的大小
int len = getlen(src_file,dst_file);
pthread_t tid;
int mid = len/2;
int end = len -len/2;
Data data = {src_file, dst_file, mid, end};
if(pthread_create(&tid, NULL, task1, &data))
{
printf("线程创建失败\n");
return -1;
}
//主线程拷贝前一半内容
copy_file(src_file, dst_file, 0, mid);
//回收子线程
pthread_join(tid, NULL);
printf("拷贝成功\n");
return 0;
}
多线程zuoye
最新推荐文章于 2024-05-30 20:15:33 发布