比较两个文本文件,打印出他们第一个不相同的行c语言
时间: 2024-03-13 22:47:23 浏览: 26
好的,我会尽力回答您的问题。以下是比较两个文本文件并打印出第一个不相同行的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
int main(int argc, char *argv[]) {
// 检查输入参数
if (argc != 3) {
fprintf(stderr, "Usage: %s <file1> <file2>\n", argv[0]);
exit(1);
}
// 打开文件
FILE *file1 = fopen(argv[1], "r");
FILE *file2 = fopen(argv[2], "r");
// 检查文件是否打开成功
if (!file1 || !file2) {
fprintf(stderr, "Error: Could not open file(s)!\n");
exit(1);
}
// 逐行比较文件内容,找到第一个不相同行
char line1[MAX_LINE_LENGTH], line2[MAX_LINE_LENGTH];
int line_number = 0;
while (fgets(line1, MAX_LINE_LENGTH, file1) && fgets(line2, MAX_LINE_LENGTH, file2)) {
line_number++;
if (strcmp(line1, line2) != 0) {
printf("First difference found on line %d:\n", line_number);
printf("%s", line1);
printf("%s", line2);
break;
}
}
// 关闭文件
fclose(file1);
fclose(file2);
return 0;
}
```
这个程序会读取两个文件的内容,逐行比较它们,并打印出第一个不相同行的行号和内容。如果两个文件完全相同,则不会输出任何内容。
希望我的回答能够帮助到您,如果您还有其他问题,请随时问我。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)