文件编程----------两个已经存在的文件当中的字符相加,写入到第三个文件;

本文介绍了一个简单的C语言程序,该程序能够读取两个文本文件中的数据,并将除去首行和末尾的数据进行相加操作后,将结果写入第三个文件。程序使用了标准的文件操作函数,如open、read和write。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾对应的数据相加,三个文本的内容如下


思路:打开两个文件,然后分别读取他们的数据,分别存放在两个缓存区当中,然后两个缓存区的数据相加,结果存到第三个缓存区,在把第三个缓存区的数据写入到第三个文件;

代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>



#define SIZE 1024

int main()
{
	int fd1 = open("text1.txt", O_RDONLY,0777);
	if(fd1 == -1)
	{
		perror("open fd1");
		return -1;
	}
	
	int fd2 = open("text2.txt", O_RDONLY,0777);
	if(fd2 == -1)
	{
		perror("open fd2");
		return -1;
	}
	
	int fd3 = open("text3.txt", O_RDWR|O_CREAT,0777);
	if(fd3 == -1)
	{
		perror("open fd3");
		return -1;
	}
	
	//读取text1内容:
	char buf1[SIZE] = {0};
	ssize_t ret1 = read(fd1, buf1, SIZE-1);

	
	if(ret1 == -1)
	{
		perror("read");
		return -1;
	}
	if(ret1 == 0) //返回值如果是0,表示已经读取到了文件的结尾;
	{
		printf("读取结束\n");
		
	}
	int len = strlen(buf1);

	//printf("读取了%d 个字节 %s",ret,buf1);
	printf("\n");
	
	
	
	//读取text2内容:
	char buf2[SIZE] = {0};
	ssize_t ret2 = read(fd2, buf2, SIZE-1);
	
	if(ret2 == -1)
	{
		perror("read");
		return -1;
	}
	if(ret2 == 0) //返回值如果是0,表示已经读取到了文件的结尾;
	{
		printf("读取结束\n");
		
	}
	//printf("读取了%d 个字节 %s",ret,buf1);
	printf("\n");
	
	
	
	//给text3写数据;
	
	int i ;
	char buf3[SIZE] ={0} ;
	for (i = 0;i < len;i++)
	{
		if(buf1[i] > '0' &&buf1[i] < '9')//判断是否是数字,是数字就相加
		{	
			buf3[i] = buf1[i] + buf2[i]-'0';
		}
		else
		{
			buf3[i] = buf1[i];
		}
	}
	

	ssize_t ret = write(fd3, buf3, strlen(buf3)); 
	if (ret == -1)
	{
			perror ("write");
	}

	return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值