我正在尝试实现比较两个文件的功能。该函数应该恢复彼此不同的第一行。如果文件相同,则返回 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;
}
最佳答案
是的,这不太好用。以下是错误:
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;
}
只需消除该 block 即可。
糟糕,忘记检查错误:
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);
}
关于C函数查找彼此不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55247475/