C 프로그래밍 언어에서 프로그래머는 파일을 초과하여 그 안에 있는 내용을 읽고 쓸 수 있습니다.
파일은 단순 메모리입니다. 정보를 저장할 수 있는 블록, 여기서는 텍스트만 관련됩니다.
이 프로그램에서는 두 파일을 비교하고 발생하는 불일치를 보고합니다. 이러한 파일은 거의 동일하지만 일부 문자가 다를 수 있습니다. 또한 프로그램은 첫 번째 불일치가 발생한 파일의 행과 위치를 반환합니다.
알고리즘
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