0

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?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
Bcpp
  • 25
  • 3

2 Answers2

2

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);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Dr. Andrey Belkin
  • 795
  • 1
  • 9
  • 28
1

You can of course but you need to save the read char. If you dont it will be lost.

int main()
{
   FILE *ptr = fopen("data.txt", "r");

   if (ptr != NULL)
   {
      int c;
      while ((c = getc(ptr)) != EOF)    //print all contents in data.txt
         printf("%c", c);
   }
   else
      printf("Open file failed.");

   return 0;
}
0___________
  • 60,014
  • 4
  • 34
  • 74