比较c中不同文本文件的字符串

时间:2016-06-30 05:15:27

标签: c string

我有两个文本文件test1.txt和test2.txt。他们每个人都有多个字符串。如果它们相同或不同,我想比较它们并打印。 我的代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char temp[100];

char const *t1;
char const *t2;

FILE *fp1=fopen("test1.txt","r");
while((t1=fgets(temp,sizeof(temp),fp1))!=NULL){
     FILE *fp2=fopen("test2.txt","r");
     while((t2=fgets(temp,sizeof(temp),fp2))!=NULL){
          if(strcmp(t1,t2)==0){
             printf("same\n");
             }
           else{
             printf("Differ\n");
             }
          }
     fclose(fp2);
     }
fclose(fp1);
}

文本文件test1.txt:

100100001
1111

的test2.txt:

10101001
1001

上面提到的代码给出了以下输出:

same
same
same
same

这显然是错误的!

我在这里做错了什么?怎么解决?

更新

我修复了代码。以下代码工作正常但请告诉我是否存在更好的解决方案:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char temp1[100];
char temp2[100];

char const *t1;
char const *t2;

FILE *fp1=fopen("test1.txt","r");
while((t1=fgets(temp1,sizeof(temp1),fp1))!=NULL){
     FILE *fp2=fopen("test2.txt","r");
     while((t2=fgets(temp2,sizeof(temp2),fp2))!=NULL){
          if(strcmp(t1,t2)==0){
             printf("same\n");
             }
           else{
             printf("Differ\n");
             }
          }
     fclose(fp2);
     }
fclose(fp1);
}

2 个答案:

答案 0 :(得分:1)

试试这个:

include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
        char temp[100];

        char t1[100];
        char t2[100];

        FILE *fp1=fopen("test1.txt","r");
        FILE *fp2=fopen("test2.txt","r");

        while((fgets(t1,100,fp1)!= NULL) && (fgets(t2,100,fp2)!= NULL))
        {

                if(strcmp(t1, t2) == 0)
                {
                        printf("same\n");
                }
                else
                {
                        printf("NOT same\n");
                }
        }

}

答案 1 :(得分:0)

不要在while循环中使用t1 当f1不等于null时,将f1中的第一个字符串复制到temp1 类似地,当f2.txt不等于null时,然后将f2中的第一个字符串cip到temp2 现在使用strcmp(temp1,temp2)比较字符串temp1和temp2 这样做直到f1.txt或f2.txt等于null

相关问题