Trouble with fgets in C: Find My Stupid Mistake

  • Thread starter Thread starter CRGreathouse
  • Start date Start date
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
1 reply · 2K views
Science Advisor
Homework Helper
Messages
2,832
Reaction score
0
I've been having trouble with reading past the end-of-file in C. Can anyone find my stupid mistake?

This is the minimal code needed to cause the error for me:

Code:
FILE *f = fopen(name, "r");
if (!f)
	return;
pari_sp ltop = avma;
char line[1100];
while(fgets(line, 1100, f) != NULL)
	printf(".");
fclose(f);

So name is a C-string pointing to a valid filename. The FILE f opens without trouble, and the fgets loop runs through each line in the file. (The actual processing code, which I deleted, parses those lines without trouble; here I replaced it with a line which shows how many lines it reads.) But the last read through fgets does *not* return NULL but causes an application-ending error. fclose is never run.

What am I doing wrong?
 
Physics news on Phys.org
Never mind, I fixed it with a rewrite. The problem must have been caused, by some mechanism I don't understand, by the surrounding (complicated) code.