Trouble with fgets in C: Find My Stupid Mistake

  • Thread starter Thread starter CRGreathouse
  • Start date Start date
Click For Summary
The discussion centers on a coding issue related to reading past the end-of-file in C. The user provided a minimal code snippet that successfully opens a file and uses fgets to read lines. However, they encountered an application-ending error on the last read attempt, where fgets did not return NULL as expected. The user noted that fclose was never executed, indicating a potential issue with error handling or file reading logic. Ultimately, they resolved the problem by rewriting the code, suggesting that the error stemmed from the surrounding, more complex code rather than the snippet itself.
CRGreathouse
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?
 
Technology 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.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 11 ·
Replies
11
Views
35K
  • · Replies 10 ·
Replies
10
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 8 ·
Replies
8
Views
6K