C 程序比较两个文件并报告不匹配
cserver side programmingprogramming更新于 2024/11/3 3:18:00
在 C 编程语言中,程序员可以复制文件并在其中读取和写入内容。
文件是可以存储信息的简单内存块,这里我们只关注文本。
在此程序中,我们将比较两个文件并报告发生的不匹配。这些文件几乎相同,但可能有一些不同的字符。此外,程序将返回发生第一个不匹配的文件的行和位置。
算法
步骤 1:打开两个文件,并在开头使用指针。 步骤 2:从文件中逐个获取字符数据。 步骤 3:比较字符。如果字符不同,则返回错误字符的行和位置。
示例
#include<stdio.h> #include<string.h> #include<stdlib.h> void compareFiles(FILE *file1, FILE *file2){ char ch1 = getc(file1); char ch2 = getc(file2); int error = 0, pos = 0, line = 1; while (ch1 != EOF && ch2 != EOF){ pos++; if (ch1 == '
' && ch2 == '
'){ line++; pos = 0; } if (ch1 != ch2){ error++; printf("Line Number : %d \tError" " Position : %d
", line, pos); } ch1 = getc(fp1); ch2 = getc(fp2); } printf("Total Errors : %d\t", error); } int main(){ FILE *file1 = fopen("file1.txt", "r"); FILE *file2 = fopen("file2.txt", "r"); if (file1 == NULL || file2 == NULL){ printf("Error : Files not open"); exit(0); } compareFiles(file1, file2); fclose(file1); fclose(file2); return 0; }
输出
// 文件内容 File1 : Hello! Welcome to tutorials Point File2: Hello! Welcome to turoials point Line number: 2 Error position: 15 Total error : 1