IO - 20230531

一. 思维导图

请添加图片描述

二. 练习

1). 使用多线程拷贝文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>

typedef struct {
	int start;
	int len;
	char src[20];
	char dest[20];
}file_info;

void copy_file(FILE *srcfp, FILE *destfp, int start, int len) {
	int count = 0;
	char buf[5];
	fseek(srcfp, start, SEEK_SET);
	fseek(destfp, start, SEEK_SET);
	while(1) {
		int read = fread(buf, 1, sizeof(buf), srcfp);
		if (read == 0 || count > len) {
			fwrite(buf, 1, read - (count - len), destfp);
			break;
		}
		fwrite(buf, 1, read, destfp);
	}
}

void *task1(void *arg) {
	file_info *info = (file_info*)arg;
	
	FILE *srcfp, *destfp;
	if ((srcfp = fopen(info->src, "r")) == NULL) {
		perror("src");
		exit(EXIT_SUCCESS);
	}
	if ((destfp = fopen(info->dest, "w")) == NULL) {
		perror("dest");
		exit(EXIT_SUCCESS);
	}
	copy_file(srcfp, destfp, info->start, info->len);
}

void *task2(void *arg) {
	file_info *info = (file_info*)arg;
	FILE *srcfp, *destfp;
	if ((srcfp = fopen(info->src, "r")) == NULL) {
		perror("src");
		exit(EXIT_SUCCESS);
	}
	if ((destfp = fopen(info->dest, "w")) == NULL) {
		perror("dest");
		exit(EXIT_SUCCESS);
	}

	copy_file(srcfp, destfp, info->start, info->len);
}

int main(int argc, const char *argv[]) {
	
	if (argc != 3) {
		printf("参数数量错误 \n");
		return -1;
	}
	FILE *fp;
	if ((fp = fopen(argv[1], "r")) == NULL) {
		printf("src open");
		return -1;
	}
	int len = fseek(fp, 0, SEEK_SET);
	fclose(fp);

	pthread_t tid1, tid2;
	
	file_info info1 = {0, len/2};
	strcpy(info1.src, argv[1]);
	strcpy(info1.dest, argv[2]);

	file_info info2 = {len/2, len/2};
	strcpy(info2.src, argv[1]);
	strcpy(info2.dest, argv[2]);

	if (pthread_create(&tid1, NULL, task1, &info1)) {
		perror("task 1");
		return -1;
	}
	if (pthread_create(&tid2, NULL, task2, &info2)) {
		perror("task 2");
		return -1;
	}
	printf("a \n");
	
	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);

	return 0;
}

结果展示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值