1210 作业

发布于:2024-12-18 ⋅ 阅读:(22) ⋅ 点赞:(0)

思维导图

作业

使用read和write函数拷贝文件,一半拷进一个文件,另一半拷进另一个文件

#include <myhead.h>
int main(int argc, const char *argv[])
{
	int fd1 = open("./z1.txt",O_RDONLY);
	if(fd1==-1)
	{
		perror("open");
		return -1;
	}
	int fd2 = open("./z2.txt",O_WRONLY|O_TRUNC|O_CREAT,0664);
	if(fd2==-1)
	{
		perror("open");
		return -1;
	}
	int fd3 = open("./z3.txt",O_WRONLY|O_TRUNC|O_CREAT,0664);
	if(fd3==-1)
	{
		perror("open");
		return -1;
	}

	char buff[1024];
	int sum = 0;
	int len = lseek(fd1,0,SEEK_END);
	printf("%d\n",len);
	lseek(fd1,0,SEEK_SET);
	/*
	   while (sum < len/2)
	   {
	   int res = sizeof(buff);
	   if (sum + res > len/2) // 如果要读取的字节数超过了半个文件
	   {
	   res = len/2 - sum; // 只读取到达半个文件的字节数
	   }

	   res = read(fd1,buff,res);
	   if (res==0) // 检查读取是否成功
	   {
	   break;
	   }
	   write(fd2,buff,res); // 写入 z2.txt
	   sum+=res; // 更新已写入的字节数
	   }
	   */
	while(1)
	{
		int res = read(fd1,buff,1);
		sum += res; 
		if(sum==len/2)
		{
			break;
		}
		write(fd2,buff,res);
	}
	while(1)
	{
		int res = read(fd1,buff,sizeof(buff));
		if(res==0)
		{
			break;
		}
		write(fd3,buff,res);
	}

	close(fd1);
	close(fd2);
	close(fd3);

	return 0;
}