Block 2 · Unit 8File Handling10 min · Section 4 of 8
8.4String Input and Output
Covers IGNOU MCS-201 §8.3.2
Reading a file one character at a time is slow to write when you really want whole lines. fgets and fputs read and write strings, normally one line at a time.
fgets
Prototype
char *fgets(char *str, int n, FILE *fp);
fgets reads characters into str until one of three things happens: it has read n - 1 characters, it has read a newline (which is stored in str), or the file ends. It then adds '\0'. It returns str on success, or NULL if the end of file was reached before any character was read (or an error occurred).
Since fgets never writes more than n bytes, it is safe against overflowing the array, which is why it replaces the unsafe gets (removed from C in 2011).
str size n
Line in file
What fgets stores
80
Hello\n
"Hello\n"
80
Hello at the very end, no newline
"Hello"
4
Hello\n
"Hel" (the rest is read by the next call)
fputs
Prototype
int fputs(const char *str, FILE *fp);
fputs writes the string without its '\0' and, unlike puts, does not add a newline. It returns a non-negative value on success and EOF on error.
Key takeaways
fgets reads up to n - 1 characters, stopping after a newline, and always adds '\0'.
It returns NULL at end of file; loop on that.
fputs writes a string and adds no newline.
A blank line is still a line ("\n").
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
A program counts lines with while (!feof(fp)) { fgets(s, 80, fp); n++; }. Explain why the count can be wrong and give the corrected loop.
Show worked answer
feof becomes true only after a read has failed at the end of the file. After the last real line is read, feof is still false, so the loop runs once more: fgets fails (returns NULL), but n is still increased, giving one line too many. The corrected loop tests the read itself: while (fgets(s, 80, fp) != NULL) n++;.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/file-handling/string-input-and-output/ to read this page.