PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] Why can't use "getc(f)) != EOF" to compare directly?

 October 30, 2022     c, eof, getc     No comments   

Issue

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?


Solution

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


Answered By - Dr. Andrey Belkin
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing