I'm new to C language, and now get stuck with this kind of question: why do I get a weird result if I use above expression to print string in file?
Here is the situation: I have a file(data.txt) with the following content:
"Hello Everyone!!"
And here is my code:
int main()
{
FILE *ptr = fopen("data.txt", "r");
if (ptr != NULL)
{
while (getc(ptr) != EOF) //print all contents in data.txt
printf("%c", getc(ptr));
}
else
printf("Open file failed.");
return 0;
}
The execution result is:
"el vroe!"
If I assign getc(ptr)
to variable first and do comparing, everything goes fine.
What's the difference between this two methods?
You extract first char in condition of while
and then extract second char in printf
. So you print only each second char in a loop.
If you want, do something like:
int c;
while ((c = getc(ptr)) != EOF) {
printf("%c", c);
}