user2759575 user2759575 - 20 days ago 5
C Question

fgetc loop returning wrong result

I'm using fgetc and a character-counting method to loop through a file of characters and return them in reverse order. Two unexpected things happen when I try and do so. When I paste a second iteration of the loop below the first it returns a very different, wacky result. As well, the first loop returns the correct result except for an additional character at the start.

For example, if the file contains the string 'Hello' the first iteration will return

5olleH
and the second
HeHeHeHeHeHeHeHeHeHeHeHeHeHe
. The correct result would be
olleH
for both loops.

Here is the code:

FILE *file = fopen( argv[1], "r" );
count = count_characters(file);
int originalCount = count;

while(count){

ch = fgetc(file);
printf("%c", ch);
fseek(file, -2L, 1); // shifts the pointer to the previous character
count--;

}

count = originalCount;

while(count){

ch = fgetc(file);
printf("%c", ch);
fseek(file, -2L, 1); // shifts the pointer to the previous character
count--;

}

Answer

It's not clear what state things are left in by count_characters(). Also at the end of the first loop, you should be at the beginning of the file (actually before it). In the second loop, you keep moving backward.

I'd set a buffer size and read the buffers from the file. For small files, read the whole thing (your algorithm should account for files smaller than the buffer). That would seem easier to me.