ctext-filesfilestreamgetcrewind

Why is rewind() not working as expected in this simple program?


Why is the below program not printing the first character of the newly created text file ("E") as expected? It's a simple program and I tried to look at the issue from all aspects but couldn't find the reason. The text file is being created on my D drive with the content "EFGHI", but for some reason "E" is not being read even if I rewind and read using getc() and the output is -1.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int x;
    FILE *fp;
    fp=fopen("F:\\demo.txt","w");
    if(fp==NULL)
        puts("Write error");
    fputs("EFGHI",fp);
    rewind(fp);

    x=getc(fp);
    printf("%d",x);
    fclose(fp);
}

UPDATED:

    #include<stdio.h>
    #include<stdlib.h>

    int main()
    {
        int x;
        FILE *fp;
        fp=fopen("F:\\demo.txt","w+");
        if(fp==NULL)
        {
            puts("Write error");
            exit(EXIT_SUCCESS);
        }
        fputs("EFGHI",fp);
        rewind(fp);

        while(!feof(fp))
        {
            x=getc(fp);
            printf("%d\n",x);
        }
        fclose(fp);
     }

Solution

  • File mode "w" opens the file for writing only.

    Use "w+" to open a file for writing and reading.

    (Please see man fopen for more file modes.)


    Regarding getc() returning -1, verbatim from man getc:

    [...] getc() [...] return[s] the character read as an unsigned char cast to an int or EOF on end of file or error.

    EOF typically equals -1. To test this do a printf("EOF=%d\n", EOF);