使用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 == '\n' && ch2 == '\n'){ line++; pos = 0; } if (ch1 != ch2){ error++; printf("Line Number : %d \tError" " Position : %d \n", 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("错误:文件未打开"); exit(0); } compareFiles(file1, file2); fclose(file1); fclose(file2); return 0; }
输出结果
// content of the files File1 : Hello! Welcome to nhooo.com File2: Hello! Welcome to nhooo.com Line number: 2 Error position: 15 Total error : 1