求教,如何合并多个文本的数据?
我想把三个文件中的数据合并带到一个文件中,文本数据有上万行。但是我初学,总也写不对程序,急请各位高手帮忙。
例如
文本1的格式为
1 2 3
2 3 4
4 5 5
文本2的格式为
2 5 7
7 43 2
24 56 22
文本3的格式为
3 4 6
2 7 5
6 7 4
求程序将以上3个文件合并为以下形式
1 2 3 2 5 7 3 4 6
2 3 4 7 43 2 2 7 5
4 5 5 24 56 22 6 7 4
[解决办法]
用两个txt的做为例子吧,3个的可以照葫芦画瓢,上代码;
111.txt内容:
aaa
bbb
ccc
ddd
222.txt内容:
111
222
333
444
将111.txt和222.txt整合到333.txt中
FILE *fh1,*fh2,*fh3;char tmp1[200],tmp2[200];fh1 = fopen("c:\\111.txt", "rb");fh2 = fopen("c:\\222.txt", "rb");fh3 = fopen("c:\\333.txt", "a");int lines = 4;//文本文件中数据的行数for(int i = 0;i<lines;i++){ fgets(tmp1,200,fh1); int index = strlen(tmp1)-2; if (tmp1[index] == 0x0d) tmp1[index] = 0x00; fgets(tmp2,200,fh2); index = strlen(tmp2)-2; if (tmp2[index] != 0x0d) { tmp2[index+2] = 0x0d; tmp2[index+3] = 0x0a; tmp2[index+4] = 0x00; } strcat(tmp1,tmp2); fwrite(tmp1, strlen(tmp1), 1, fh3);}fclose(fh1);fclose(fh2);fclose(fh3);
[解决办法]
#include <stdio.h>#include <string.h>#define MAXLEN 80FILE *f1,*f2,*f3,*f4;char s1[MAXLEN];char s2[MAXLEN];char s3[MAXLEN];int L;int main() { f1=fopen("1.txt","r"); if (NULL==f1) {printf("Can not fopen 1.txt!\n");return 1;} f2=fopen("2.txt","r"); if (NULL==f2) {printf("Can not fopen 2.txt!\n");return 1;} f3=fopen("3.txt","r"); if (NULL==f3) {printf("Can not fopen 3.txt!\n");return 1;} f4=fopen("4.txt","w"); if (NULL==f4) {printf("Can not fopen 4.txt!\n");return 1;} while (1) { if (NULL==fgets(s1,MAXLEN,f1)) break;L=strlen(s1);s1[L-1]=0; if (NULL==fgets(s2,MAXLEN,f2)) break;L=strlen(s2);s2[L-1]=0; if (NULL==fgets(s3,MAXLEN,f3)) break;L=strlen(s3);s3[L-1]=0; fprintf(f4,"%s %s %s\n",s1,s2,s3); } fclose(f4); fclose(f3); fclose(f2); fclose(f1); return 0;}