Buzz Black Buzz Black - 1 month ago 6
C Question

Comparing two files char by char - end of file error in C

I have a specific problem. I have to read Strings from two files and compare them char by char, and tell in which row is the difference and for how many chars they differ. I have made pointer and all stuff, but the problem is when it comes to the end of the first file (it needs to read just for the length of the shorter file) I am unable to compare the last String because my for loop goes till the '\n', and in last row there is no \n. But on the other side if I put '\0' in for loop it gives me a wrong result, because it counts '\n' as char as well. How do I handle this problem? Suggestions? I don't want to use strcmp() since I need to count char difference, and there are some other conditions to be fulfilled. Here is my problem:

while(!feof(fPointer)){
zeichnen = 0;
fgets(singleLine, 150, fPointer);
fgets(singleLine2, 150, fPointer2);
length = strlen(singleLine); // save the length of each row, in order to compare them
length2 = strlen(singleLine2);
if(length <= length2){
for(i=0; singleLine[i] != '\n'; i++){
singleLine[i] = tolower(singleLine[i]);
singleLine2[i] = tolower(singleLine2[i]);
if(singleLine[i] != singleLine2[i]){
zeichnen++;
}
}
printf("Zeile: %d \t Zeichnen: %d\n", zeile, zeichnen); // row, char

Answer
for(i=0; i < min(length, length2); i++) {
      if ( singeLine[i] == '\n' || singleLine2[i] == '\n')
        break;
       /* Do work */
}       

Alternative is to use logical and operator to test two or more conditions in for loop conditional part.

From fgets manual page:

char *fgets(char *s, int size, FILE *stream);

fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.

So you chould have while(true) loop and check both fgets return values for end of input.