2个文件之间的区别

时间:2016-12-12 18:25:53

标签: c

我试图找出两个文件之间的区别:

Car
Wine
Man
Nobody
Car
Shoes
Cookies

我希望程序显示第一个文件中的单词,而不是第二个文件中的单词,如下所示:

Wine
Man

这是我试过的:

#include<stdio.h>
#include<stdlib.h>
#define STORE 300
void file1(char*line,char*line1){
    if(strcmp(line,line1)<0){
        printf("%s",line);
    }
}
int main(){
    FILE *fp1, *fp2;
    fp1=fopen("file1.txt","r");
    fp2=fopen("file2.txt","r");
    char buff[STORE], buff1[STORE];
    while(fgets(buff,STORE,fp1)!=NULL){
        while(fgets(buff1,STORE,fp2)!=NULL){
            file1(buff,buff1);
        }
        rewind(fp2);
    }
}

我的输出是:

Car
Car
Car
ManMan

为什么我没有得到我期待的输出?

1 个答案:

答案 0 :(得分:0)

背景:

这是你的课程用英语做的。

Car is alphabetically before Nobody, so print it.
Car is NOT before Car, so do NOT print it.
Car is before Shoes -> print
Car is before Cookies -> print
Wine is NOT before Nobody (or anything) -> do NOT print
Man is before Nobody -> print
Man is NOT before Car -> do NOT print
Man is before Shoes -> print
Man is NOT before Cookies -> do NOT print

因此,你的结果: 汽车,汽车,汽车,男人,男人

第1步: 你的strcmp()调用需要是!= 0而不是&lt; 0。 你从不打印葡萄酒的原因&#39;是因为strcmp(&#34; wine&#34;,&#34; nobody&#34;)是&gt; 0,所以它不打印Wine(永远)

步骤2:void file1()函数如果匹配则返回1,如果不匹配则返回0,将它们相加并仅在总和为0时打印该行。这是非常低效的,但是...将...完成工作。

第3步(也许?)你是否错过了最后一句&#34; Man&#34;什么东西导致它打印曼曼?

int file1(char*line,char*line1){
   if(strcmp(line,line1)!=0)  /* note correct comparison */
       return 0;
   else
       return 1;
}

...

int match = 0;
while(fgets(buff,STORE,fp1)!=NULL){
    match = 0;
    while(fgets(buff1,STORE,fp2)!=NULL){
        match += file1(buff,buff1);
    }
    if (match == 0) { /* it never matched so print it */
        printf("%s", buff);
    }
    rewind(fp2);
}