โจทย์
เปรียบเทียบไฟล์ข้อความสองไฟล์ที่คล้ายกัน แต่มีตัวอักษรบางตัวต่างกัน โปรแกรมจะรายงานตำแหน่งที่แตกต่างครั้งแรก (บรรทัดและตำแหน่ง) และนับจำนวนข้อผิดพลาดทั้งหมด
อัลกอริทึม
- เปิดทั้งสองไฟล์ด้วย pointer ชี้ที่จุดเริ่มต้น
- อ่านข้อมูลทีละตัวอักษร (character) จากทั้งสองไฟล์
- เปรียบเทียบตัวอักษร: ถ้าต่างกัน ให้บันทึกหมายเลขบรรทัดและตำแหน่ง
- นับบรรทัดเมื่อเจอ \n และรีเซ็ตตำแหน่ง
- แสดงผลรวมข้อผิดพลาด
โค้ดภาษา C
#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(file1);
ch2 = getc(file2);
}
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 Errors: 1