/* text1.txt text2.txt text3.txt begin begin begin 10 11 12 15 16 17 25 27 29 20 21 22 25 26 27 45 47 49 30 31 32 35 36 37 65 67 69 end end end */ //open read write #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define SIZE 520 int main() { //打开一个新文件text3.txt char buf3[SIZE] = {0}; int fd = open ("text3.txt",O_RDWR | O_CREAT,0777); if(fd == -1) { perror("open fd"); return -1; } //将text1.txt内容复制给字符数组 char buf1[SIZE] = {0}; int fd1 = open ("text1.txt",O_RDWR,0777); if(fd1 == -1) { perror("open fd1"); return -1; } ssize_t ret1 = read (fd1,buf1,SIZE-1); if(ret1 == -1) { perror("read "); } if(ret1 == 0) { printf("read over\n"); } printf("text1.txt \n"); printf("%s\n",buf1); printf("\n"); printf("\n"); //将text2.txt内容复制给字符数组 char buf2[SIZE] = {0}; int fd2 = open ("text2.txt",O_RDWR,0777); if(fd2 == -1) { perror("open fd2"); return -1; } ssize_t ret2 = read (fd2,buf2,SIZE-1); if(ret2 == -1) { perror("read "); } if(ret2 == 0) { printf("read over\n"); } printf("text2.txt \n"); printf("%s\n",buf2); printf("\n"); strcpy(buf3,buf2);//将一个字符串复制到另一个字符数组中去 int i = 0; while(buf2[i] != '\0') //遍历字符数组 { if(buf2[i] >= '0' && buf2[i] <= '9')//判断是否是数字 { //buf1[i] 与 buf2[i]一起进行判断 buf3[i] = buf1[i] + buf2[i] - '0';//将字符型数据转化为整型数据 } i++; } int len = strlen(buf1); write (fd,buf3,len); /* write()系统调用向打开的文件写数据。 #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); Returns number of bytes written, or –1 on error fd:要写入的文件的描述符。 buf:要写入的数据所存放的缓冲区。 count:要写入的字节数。 返回值:若成功返回已写的字节数,出错则返回-1并设置变量errno的值 */ printf("text3.txt \n"); printf("%s\n",buf3); close(fd); close(fd1); close(fd2); return 0; } //fopen fread fwrite #include <stdio.h> #include <string.h> #define SIZE 1024 int main() { FILE *fp1 = fopen ("text1.txt","ab+");//以读和写方式打开 FILE *fp2 = fopen ("text2.txt","ab+"); if(fp1 == NULL) { perror("fopen fp1 "); return -1; } if(fp2 == NULL) { perror("fopen fp2 "); return -1; } FILE *fp3 = fopen ("text3.txt","ab+"); if(fp3 == NULL) { perror("fopen fp3"); return -1; } char buf1[SIZE] = {0}; char buf2[SIZE] = {0}; char buf3[SIZE] = {0}; int ret; while(ret = fread(buf1,sizeof(char),SIZE-1,fp1)) { buf1[ret*sizeof(char)] = '\0'; printf("%s\n",buf1); printf("\n"); } int ret2; while(ret2 = fread(buf2,sizeof(char),SIZE-1,fp2)) { buf2[ret2*sizeof(char)] = '\0'; printf("%s\n",buf2); } strcpy(buf3,buf1); int i = 0; while(buf2[i] != '\0') { if(buf2[i] >= '0' && buf2[i] <= '9') { buf3[i] = buf1[i] + buf2[i] - '0'; } i++; } int len = strlen(buf1); //要传输的数据个数,不是字节长度 fwrite(buf3,sizeof(char),len,fp3); /* #include <stdio.h> fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream); 数据从文件流stream读到ptr指向的数据缓冲区里。 size参数指定每个数据记录的长度, nmemb给出要传输的记录的个数。 函数的返回值是成功读到数据缓冲区里的记录的个数(不是字节数) */ printf("\n"); printf("%s\n",buf3); printf("\n"); fclose(fp1); fclose(fp2); fclose(fp3); return 0; }
手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾对应的数据相加
最新推荐文章于 2023-01-07 17:39:43 发布