C函数查找彼此不同的行

时间:2019-03-19 18:10:52

标签: c

我正在尝试实现比较两个文件的功能。该功能应恢复彼此不同的前几行。如果文件相同,则将返回NULL。该函数在两个文件之一结束时立即结束,然后返回NULL。我认为我的if函数不起作用,因此该函数不会返回行。

这是我的代码:

char *difference(const char* file1, const char* file2)
{
    char line1[1000];
    char line2[1000];
    char *a = malloc(1000 * sizeof(char));

    FILE *f1 = fopen(file1, "r");
    FILE *f2 = fopen(file2, "r");
    if (!f1 || !f2) // checking if there is any error 
    {
        return -1; 
    }

    while (fgets(line1, sizeof(line1), file1) != NULL && fgets(line2, sizeof(line2), file1) != NULL)
{
    if (strcmp(line1, line2) != 0)
    {
        strcpy(a, line1);
        strcpy(a, line2);

    }
    else
    {
        return NULL;
    }
}

fclose(f1);
fclose(f2);
return a;

int main(void)

    char* diff = difference("testifile.c", "testifile2.c");
    printf("\n--- Difference:\n");
    printf("%s", diff);

    free(diff);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

是的,效果不佳。这些错误:

return -1;

不编译。你是说

return (char*)-1;

此外,还会泄漏内存。做:

 if (f1) fclose(f1);
 if (f2) fclose(f2);
 return (char*)-1;

您从file1读过两次的糟糕消息:

while (fgets(line1, sizeof(line1), file1) != NULL && fgets(line2, sizeof(line2), file1) != NULL)

应该是

while (fgets(line1, sizeof(line1), file1) != NULL && fgets(line2, sizeof(line2), file2) != NULL)

内存浪费:

line3=strcat(line1,line2);

应该是:

strcat(strcpy(a,line1),line2);

只检查第一行,因为提前返回:

else
{
    return NULL;
}

只需消除该障碍。

糟糕,忘记检查错误了:

char* diff = difference("testifile.c", "testifile2.c");

char* diff = difference("testifile.c", "testifile2.c");
if (diff == (char *)-1) {
    /* handle file open error */
}
else if (diff == NULL) {
    /* handle no difference */
}
else {
     /* your message */
     free(diff);
}