开发者

How to determine, inside of "while(fscanf != EOF){blah}", if the next fscanf is going to return EOF?

开发者 https://www.devze.com 2022-12-28 12:45 出处:网络
I\'ve got some code executing in a while(fscanf != EOF) loop. How开发者_如何学Cever, even when fscanf has finished executing, I need to keep running that code until some conditions are met.

I've got some code executing in a while(fscanf != EOF) loop. How开发者_如何学Cever, even when fscanf has finished executing, I need to keep running that code until some conditions are met. I mean I guess I could copy/paste the code to outside the while(fscanf) loop, and only use global variables, but that seems messy. Surely someone has encountered something like this before and has a cleaner solution.


Couldn't you just modify the while condition to account for these additional conditions?

while(fscanf(...) != EOF || !(some_other_conditions_met)) 


You can't - the feof() function only tests for the end of file condition after a a read operation - there is no way of testing if the next operation will fail. You need to change the logic of your program, as C stream I/O doesn't directly support what you are asking for.


The answer to the title of your question is that it's pretty well impossible. Imagine getting a random number and deciding which of two format strings you're going to pass to fscanf. You want an advance prediction whether fscanf will get eof when you don't even know what the random number will be?

The answer to the body of your question is more or less what Andreas Brinck wrote. I have a feeling you might need something more like this though:

for (;;)
{
  // .....
  eofReached = (fscanf(..) == EOF);
  // .....
  if (eofReached && otherConditionsMet) break;
  // .....
}


Cleaner solutions avoid using scanf/fscanf. It's much less error-prone to read an entire line at a time and to parse the line with sscanf instead.

From the comp.lang.c FAQ: Why does everyone say not to use scanf? What should I use instead?

The entry on feof usage is also relevant.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号