Why doesn't rewind () work as expected in this simple program?

Why doesn't the program below print the first character of a newly created text file ( "E" ) as expected? This is a simple program, and I tried to consider this problem from all sides, but could not find the reason. The text file is created on my D-disk with the contents of " EFGHI ", but for some reason "E" is not readable, even if I rewind and read with the help getc()and the -1 output .

#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);
     }
+4
source share
2 answers

"w" .

"w+", .

( . man fopen.)


getc() -1, man getc:

[...] getc() [...] [s] , unsigned char, int EOF .

EOF -1. , printf("EOF=%d\n", EOF);

+7

fp=fopen("F:\\demo.txt","w");

, . .

, fp, , if fp , .

+4

Source: https://habr.com/ru/post/1613507/


All Articles