-
-
不爱榴莲
丨Lv 0
你的程序思路在内层循环哪儿有些混乱,实现不了你所要求的功能,按照以下代码改就对了;fgets()函数读取的字符串里含有空格,比如他第一次读取的是"hejie tianjing",这样就无法进行下面的比较,所以用fscanf(fp,"s",buf)代替。下面是改正后的代码:#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> #define null NULLint main() { FILE *fptr1,*fptr2,*fptr3; char temp[15],temp1[15],temp2[15]; if((fptr1=fopen("a.txt","r"))==null) { printf("can not open file"); exit(0); } if((fptr2=fopen("b.txt","r"))==null) { printf("can not open file"); exit(0); } if((fptr3=fopen("ab.txt","w"))==null) { printf("can not open file"); exit(0); } //clrscr(); //while(strlen(fgets(temp1,15,fptr1))>1) while(fscanf(fptr1,"%s",temp1)!=EOF) { fgets(temp2,15,fptr1); fputs(temp1,fptr3); fputs(temp2,fptr3); strcpy(temp,temp1); do { if(fscanf(fptr2,"%s",temp2)==EOF) { printf("Something Error!\n"); exit(1); } }while(strcmp(temp,temp2)!=0); fgets(temp2,15,fptr2); fputs(temp2,fptr3); rewind(fptr2); } fclose(fptr1); fclose(fptr2); fclose(fptr3); } ab.txt内容:hejie tianjing 8764 liying shanghai 12345 liming chengdu 7654322 wangpin chongqing 87643 linux里conio.h在那里不知道还有,clrscr()函数值在TC里有吧?我用的是VC,所以找不见那个函数,将它注释掉了。你的新要求的参考答案:#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> #define null NULLint main() { FILE *fptr1,*fptr2,*fptr3; int lock=0; char temp[15],temp1[15],temp2[15],temp3[15]; if((fptr1=fopen("a.txt","r"))==null) { printf("can not open file"); exit(0); } if((fptr2=fopen("b.txt","r"))==null) { printf("can not open file"); exit(0); } if((fptr3=fopen("ab.txt","w"))==null) { printf("can not open file"); exit(0); } //clrscr(); //while(strlen(fgets(temp1,15,fptr1))>1) while(fscanf(fptr1,"%s",temp1)!=EOF) { fgets(temp2,15,fptr1); strcpy(temp3,temp2); //fputs(temp1,fptr3); //fputs(temp2,fptr3); strcpy(temp,temp1); do { if(fscanf(fptr2,"%s",temp2)==EOF) {// printf("Something Error!\n"); lock=1; break;// exit(1); } }while(strcmp(temp,temp2)!=0); if(lock==1) { lock=0; rewind(fptr2); continue; } lock=0; fputs(temp1,fptr3); fputs(temp3,fptr3); fgets(temp2,15,fptr2); fputs(temp2,fptr3); rewind(fptr2); } fclose(fptr1); fclose(fptr2); fclose(fptr3);} /*a.txt:hejie 23 hunan 45 shanghai 12 b.txt:hejie K hubei H shanghai G ab.txt:hejie 23 K shanghai 12 G *//*********************小恩 制作********************/