文件編程----------兩個已經存在的文件當中的字符相加,寫入到第三個文件;

題目:手動創建兩個文本文件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;
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章