ในภาษาซี โปรแกรมเมอร์สามารถขยายไฟล์และอ่านและเขียนเนื้อหาได้
ไฟล์คือ หน่วยความจำที่เรียบง่าย บล็อคที่สามารถเก็บข้อมูลได้ ที่นี่เราเน้นเฉพาะข้อความเท่านั้น
ในโปรแกรมนี้ เราจะเปรียบเทียบสองไฟล์และรายงานความไม่ตรงกันที่เกิดขึ้น ไฟล์เหล่านี้เกือบจะเหมือนกัน แต่อาจมีอักขระบางตัวที่แตกต่างกัน นอกจากนี้โปรแกรมจะส่งคืนบรรทัดและตำแหน่งของไฟล์ที่เกิดไม่ตรงกันครั้งแรก
อัลกอริทึม
Step 1: Open both the file with pointer at the starting. Step 2: Fetch data from file as characters one by one. Step 3: Compare the characters. If the characters are different then return the line and position of the error character.
ตัวอย่าง
#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("Error : Files not open");
exit(0);
}
compareFiles(file1, file2);
fclose(file1);
fclose(file2);
return 0;
} ผลลัพธ์
// content of the files File1 : Hello! Welcome to tutorials Point File2: Hello! Welcome to turoials point Line number: 2 Error position: 15 Total error : 1