c语言比较两个文本文件是否相等:比较两个文本文件的内容是否相同,并输出两个文件中第一次出现不同字符内容的行号及列值。试编写相应程序。
时间: 2023-06-07 16:09:13 浏览: 235
好的,下面是C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_SIZE 1024
int compare_file(const char* file1, const char* file2);
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("Usage: %s [file1] [file2]\n", argv[0]);
return 0;
}
const char* file1 = argv[1];
const char* file2 = argv[2];
int ret = compare_file(file1, file2);
if (ret == 0) {
printf("Files are identical.\n");
}
return 0;
}
int compare_file(const char* file1, const char* file2) {
FILE* fp1 = fopen(file1, "r");
FILE* fp2 = fopen(file2, "r");
if (!fp1 || !fp2) {
printf("Failed to open file.\n");
return -1;
}
char line1[MAX_LINE_SIZE];
char line2[MAX_LINE_SIZE];
int line_num = 0;
int col_num = 0;
while (fgets(line1, MAX_LINE_SIZE, fp1) && fgets(line2, MAX_LINE_SIZE, fp2)) {
line_num++;
if (strcmp(line1, line2) != 0) {
// Find the position of the first difference
col_num = 0;
while (line1[col_num] == line2[col_num] && line1[col_num] != '\0') {
col_num++;
}
printf("Files are different at line %d, col %d:\n", line_num, col_num+1);
printf("%s", line1);
printf("%s", line2);
return -1;
}
}
if (fgets(line1, MAX_LINE_SIZE, fp1) || fgets(line2, MAX_LINE_SIZE, fp2)) {
printf("Files have different number of lines.\n");
return -1;
}
fclose(fp1);
fclose(fp2);
return 0;
}
```
该程序会读入两个文件的路径,然后逐行比对两个文件的内容。如果发现不同,就输出不同的位置信息和相应的行内容。如果比对完整个文件后两者相同,就输出提示信息。
阅读全文