fgets and fputs
- C course
- Intermediate
- Lesson 49/116
- 5 min
Learn to read and write lines with fgets and fputs.
fgets and fputs
fgets and fputs are the basic way to read and write lines to/from a file. fgets includes the newline character; fputs doesn't add an automatic newline.
Example: fputs("Merhaba\n", f); writes a line to the file. char line[64]; fgets(line, sizeof(line), f); reads a line from the file. The second parameter of fgets is the maximum bytes to read; this prevents overflow. fgets returns NULL at end of file; this feature is used to read all lines with a loop.
EOF and NULL
fgets returns NULL at end of file. This feature is used to read all lines with a loop. The NULL check is the loop's stop condition.
Example: while (fgets(line, sizeof(line), f) != NULL) { printf("%s", line); }. This loop prints every line of the file to the screen. Because fgets includes the newline, printf doesn't add an extra \n. This pattern is standard for processing text files; log files, configuration files and reports are read this way.
Practice Write a line, read back and print
Open with FILE *f = fopen("line.txt", "w"); (check NULL). Write with fputs("Merhaba dünya\n", f);, fclose(f);. Reopen with f = fopen("line.txt", "r");. Declare char line[64];; read with fgets(line, sizeof(line), f);. fclose(f);. Print with printf("%s", line);.
Starter code
#include <stdio.h>
// Open line.txt with fopen (write mode)
// Write a line with fputs
// fclose, then reopen in read mode
// Read with fgets, print with printf
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
FILE *f = fopen("line.txt", "w");
if (f == NULL) return 1;
fputs("Merhaba dünya\n", f);
fclose(f);
f = fopen("line.txt", "r");
if (f == NULL) return 1;
char line[64];
fgets(line, sizeof(line), f);
fclose(f);
printf("%s", line);
return 0;
}Expected output
Merhaba dünya
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the fgets call
fgets(line, ____, f);
fgets(line, sizeof(line), f);
Explanation: sizeof(line) is the size limit that prevents overflow.
2 Match functions to purpose
| Term | Meaning |
|---|---|
fgets |
Line read |
fputs |
String write |
sizeof(line) |
Size limit |
NULL |
EOF indicator |
3 What does fgets return at end of file?
- -1
- 0
- NULL Correct answer
- EOF
Explanation: fgets returns NULL at EOF; this is used as a loop condition.