views:

202

answers:

4

I've got some code executing in a while(fscanf != EOF) loop. However, 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.

+3  A: 

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

while(fscanf(...) != EOF || !(some_other_conditions_met)) 
Andreas Brinck
lol. It's getting late. edit: actually, there's code I don't want executed once EOF is reached.I think I'll have to split it out.
Rancur3p1c
+1  A: 

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.

anon
+1  A: 

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;
  // .....
}
Windows programmer
A: 

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.

jamesdlin