Pregunta

I this code is used for reading the text file in reverse order. And it successful does, displaying the original content of file and the reversed content of file.

#include <stdio.h>
#include <stdlib.h>
int main()  {

    int count = 0, ch = 0;
    FILE *fp;
    if( (fp = fopen("file.txt", "r")) == NULL )    {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    printf("\tINPUT FILE\n");
    printf("\n");
    while(!feof(fp))    {
        if((ch = getc(fp)) != EOF)  {
            printf("%c", ch);
            count ++;
        }
    }
    feof(fp);
    printf("\n");
    printf("\tREVERSED INPUT FILE\n");
    printf("\n");
    while(count)    {
        fseek(fp, -2, SEEK_CUR);
        printf("%c", getc(fp));
        count--;
    }
    printf("\n");
    fclose(fp);
}

But when i replaced, this piece of code

while(!feof(fp))    {
   if((ch = getc(fp)) != EOF)  {
       printf("%c", ch);
       count ++;
   }
}

by

fseek (fp, 0, SEEK_END); or  feof(fp);

Basically i just went till end of file and directly without printing the original contents of file and tried printing the reversed content of file. But for it does not print the reversed content filed either !!! it just display blank. Why is this happening ??

NOTE: fseek(fp, -2, SEEK_CUR); Have done this (in another while loop) as getc(fp) moves fp forward by one so need to rewind it back by two, also initially it will be pointing to EOF

What is happening here? Can any one please explain?

¿Fue útil?

Solución

It breaks because the second loop is while (count), and count is zero if you haven't read through the file first while incrementing it. You can use ftell to obtain the equivalent of count in this case.

P. S. feof(fp) only tests whether fp is at end-of-file, it does not make it seek to EOF, so the line feof(fp) basically does nothing since you aren't using the return value.

Otros consejos

As @Arkku already showed, when you replace the while loop with fseek(SEEK_END), count will not be incremented.

To fix this, you can use ftell after fseek, which returns the file length

fseek(fp, 0, SEEK_END);
count = ftell(fp);

Now the file will be printed backwards.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top