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);
}
source
share