I'm developing on Windows (VS 2010) a simple program using fgetc and I recognized that after I'm using this function (same behavior with getc) I can't write to the file although I opened it with appropriate permissions.
Here is a simple program I wrote to check what the hell is going on:
int main(int argc, char * argv[])
{
FILE *f = NULL;
char ch = 0;
int bytes = 0;
f = fopen(argv[1], "r+");
ch = fgetc(f);
bytes = fwrite("1234", sizeof(char), 4, f);
printf("%d", bytes);
fflush(f);
fclose(f);
system("PAUSE");
return 0;
}
The program prints 4 and exit without any error, but the file content remain the same. After I research it a little bit I found out that if I add this line (that doing "nothing"):
fseek(f, 0, SEEK_CUR);
The program working as I expected, and the file content changed.
all the code after adding this line:
int main(int argc, char * argv[])
{
FILE *f = NULL;
char ch = 0;
int bytes = 0;
f = fopen(argv[1], "r+");
ch = fgetc(f);
fseek(f, 0, SEEK_CUR)
bytes = fwrite("1234", sizeof(char), 4, f);
printf("%d", bytes);
fflush(f);
fclose(f);
system("PAUSE");
return 0;
}
Does anyone know why is this happen and how to solve it?
Thanks a lot, Hanan.