Reading and Writing Text Files
C gives you three pairs of functions for text files. One works character by character, one line by line, and one with formats like printf. Picking the right pair makes file programs short and simple.
In this lesson you will use all three pairs, learn how to detect the end of file (EOF) correctly, and write programs that count characters, words and lines, and process formatted records.
What You Will Learn
fputcandfgetc: one character at a time.fputsandfgets: one line at a time.fprintfandfscanf: formatted data.- What EOF is and how to check for it.
- Why
fgetc's result must be stored in anint. - Which function to choose for a task.
Text File Functions Explained
Exam definition: fgetc/fputc read/write one character; fgets/fputs read/write one string (line); fscanf/fprintf read/write formatted data. EOF is a negative integer constant (usually −1) returned by input functions when the end of the file is reached or an error occurs.
Memory trick: Think of reading a book. fgetc = reading letter by letter (slow but full control). fgets = reading line by line. fscanf = filling a form: you know which box (roll, name, marks) comes next. The "f" in front just means "file version".
Syntax of Text File Functions
| Function | Prototype | Returns at end/error |
|---|---|---|
fputc | int fputc(int c, FILE *fp); | EOF on error |
fgetc | int fgetc(FILE *fp); | EOF |
fputs | int fputs(const char *s, FILE *fp); | EOF on error (does not add '\n') |
fgets | char *fgets(char *s, int n, FILE *fp); | NULL (keeps '\n') |
fprintf | int fprintf(FILE *fp, const char *fmt, ...); | Negative on error |
fscanf | int fscanf(FILE *fp, const char *fmt, ...); | Items read, or EOF |
The right way to loop until EOF
int ch; /* int, not char! */
while ((ch = fgetc(fp)) != EOF) { ... }
char line[100];
while (fgets(line, sizeof line, fp) != NULL) { ... }
while (fscanf(fp, "%d %s", &roll, name) == 2) { ... }
Why int ch? fgetc returns any char value (0–255) or EOF (−1). A char can't hold all 257 possibilities, so EOF might be confused with a real character. Store the result in an int.
Example 1: Character and Line Functions (Count Characters, Words, Lines)
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *fp;
const char *text = "C is fast.\nC is portable.\nLearn C today!\n";
int i, ch, chars = 0, lines = 0, words = 0, in_word = 0;
char line[80];
fp = fopen("poem.txt", "w");
if (fp == NULL)
return 1;
for (i = 0; text[i] != '\0'; i++) /* write char by char */
fputc(text[i], fp);
fclose(fp);
fp = fopen("poem.txt", "r");
if (fp == NULL)
return 1;
while ((ch = fgetc(fp)) != EOF) /* read char by char */
{
chars++;
if (ch == '\n')
lines++;
if (isspace(ch))
in_word = 0;
else if (!in_word)
{
in_word = 1;
words++;
}
}
fclose(fp);
printf("Characters: %d, Words: %d, Lines: %d\n", chars, words, lines);
fp = fopen("poem.txt", "r"); /* now line by line */
if (fp == NULL)
return 1;
i = 1;
while (fgets(line, sizeof line, fp) != NULL)
printf("%d: %s", i++, line);
fclose(fp);
remove("poem.txt");
return 0;
}
Output
Characters: 41, Words: 9, Lines: 3 1: C is fast. 2: C is portable. 3: Learn C today!
Code Explanation
fputc(text[i], fp)writes one character at a time, including the'\n'characters.while ((ch = fgetc(fp)) != EOF)reads one character per loop and stops at the end of the file. The brackets around the assignment are required.- Counting newlines gives the number of lines. Counting the start of each non-space run gives the words.
fgetsreads a full line, including its'\n', soprintf("%d: %s", ...)doesn't need another newline.
How fscanf and fprintf Handle Records
fprintf writes values with a format, and fscanf reads them back with the same format. fscanf returns how many items it matched, which is the cleanest loop condition.
fprintf(fp, "%d %s %d\n", roll, name, marks); -> file line: "101 Asha 88"
fscanf (fp, "%d %s %d", &roll, name, &marks); -> returns 3 while records remain
returns EOF at the end
Remember: %s stops at a space, so names with spaces need fgets (or a different separator, like a comma, with %[^,]).
Example 2: Marks File with fprintf and fscanf, Report with fputs
#include <stdio.h>
int main(void)
{
FILE *fp, *rep;
int roll, marks, best_roll = 0, best = -1, count = 0, pass = 0;
char name[20], best_name[20] = "";
char line[80];
int i;
int r[] = {101, 102, 103, 104};
const char *n[] = {"Asha", "Ravi", "Neha", "Arjun"};
int m[] = {88, 34, 95, 61};
fp = fopen("marks.txt", "w");
if (fp == NULL)
return 1;
for (i = 0; i < 4; i++)
fprintf(fp, "%d %s %d\n", r[i], n[i], m[i]);
fclose(fp);
fp = fopen("marks.txt", "r");
rep = fopen("report.txt", "w");
if (fp == NULL || rep == NULL)
return 1;
while (fscanf(fp, "%d %19s %d", &roll, name, &marks) == 3)
{
count++;
if (marks >= 40)
pass++;
if (marks > best)
{
best = marks;
best_roll = roll;
sprintf(best_name, "%s", name);
}
fputs(marks >= 40 ? "PASS " : "FAIL ", rep);
fprintf(rep, "%s\n", name);
}
fclose(fp);
fclose(rep);
printf("Students: %d, Passed: %d\n", count, pass);
printf("Topper : %d %s (%d)\n", best_roll, best_name, best);
rep = fopen("report.txt", "r");
if (rep == NULL)
return 1;
printf("Report file:\n");
while (fgets(line, sizeof line, rep) != NULL)
fputs(line, stdout); /* fputs to the screen */
fclose(rep);
remove("marks.txt");
remove("report.txt");
return 0;
}
Output
Students: 4, Passed: 3 Topper : 103 Neha (95) Report file: PASS Asha FAIL Ravi PASS Neha PASS Arjun
- Two files are open at once: one for reading (marks.txt) and one for writing (report.txt). Each has its own FILE pointer.
fputswrites a string without adding a newline, so the line is finished by the followingfprintf.fputs(line, stdout)shows that the screen is just another stream.
Practice: C program to write and read a text file.
Which Function Should You Use?
| Task | Best choice |
|---|---|
| Count characters, copy a file exactly, encrypt letters | fgetc / fputc |
| Process line by line, read text with spaces | fgets / fputs |
| Numbers and fields in a fixed format | fscanf / fprintf |
Important Points to Remember
- fgetc/fputc = character; fgets/fputs = line; fscanf/fprintf = formatted.
- Store fgetc's result in an int and compare with EOF.
- fgets returns NULL at end and keeps the '\n'.
- fputs does not add a newline (unlike puts).
- fscanf returns the number of items read; loop while it equals the expected count.
- Read with the same format you wrote with.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
char ch = fgetc(fp); | EOF may be missed or a real byte mistaken for EOF | int ch |
while (!feof(fp)) then read | Last record processed twice | Loop on the read function's return value |
while (ch = fgetc(fp) != EOF) | ch becomes 0/1 (precedence) | while ((ch = fgetc(fp)) != EOF) |
Reading names with spaces using %s | Fields shift, wrong data | Use fgets or a separator |
| Expecting fputs to add '\n' | Lines run together | Add "\n" yourself |
Text File Functions Practice Questions
- Name the three pairs of text file functions.
- Why should the result of fgetc be stored in an int?
- What does fgets return at the end of a file?
- What is the difference between puts and fputs?
- Why is
while (!feof(fp))a bad loop condition?
Show answers
- fgetc/fputc, fgets/fputs, fscanf/fprintf.
- It returns any character value or EOF (−1); a char can't safely represent all of these.
- NULL.
- puts writes to the screen and adds a newline; fputs writes to any stream and adds no newline.
- feof becomes true only after a read fails, so the loop body runs once more with stale data.
Coding Exercise
Write "hello world from c" to a file, then read it with fgetc and print it with the first letter of every word in capitals (use toupper).
Show solution
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *fp = fopen("words.txt", "w");
int ch, new_word = 1;
if (fp == NULL)
return 1;
fputs("hello world from c\n", fp);
fclose(fp);
fp = fopen("words.txt", "r");
if (fp == NULL)
return 1;
while ((ch = fgetc(fp)) != EOF)
{
if (new_word && isalpha(ch))
{
ch = toupper(ch);
new_word = 0;
}
if (isspace(ch))
new_word = 1;
putchar(ch);
}
fclose(fp);
remove("words.txt");
return 0;
}
Hello World From C
Quick Quiz: Reading and Writing Text Files (MCQ)
-
Which function reads one line from a file?
A)
fgetcB)fgetsC)fputsD)fprintf -
fgetc returns what at the end of a file?
A) NULL B) 0 C) EOF D) '\0'
-
fscanf(fp, "%d %d", &a, &b)returns what when both numbers are read?A) 0 B) 1 C) 2 D) EOF
-
Which adds a newline automatically?
A)
fputsB)putsC)fputcD)fprintf -
The variable holding fgetc's result should be:
A)
charB)intC)floatD)char *
Show answers
- B:
fgets. - C: EOF.
- C: 2.
- B:
puts. - B:
int.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Character I/O | fgetc / fputc |
|---|---|
| Line I/O | fgets / fputs |
| Formatted I/O | fscanf / fprintf |
| End markers | fgetc/fscanf → EOF; fgets → NULL |
| fgetc result type | int |
| fputs | No automatic newline |
| Loop condition | The read function's return, not feof |
Frequently asked questions
- How do you read a file line by line in C?
- Use while (fgets(line, size, fp) != NULL).
- What is EOF?
- A negative constant (usually −1) returned when the end of file is reached or an error occurs.
- What is the difference between fprintf and fputs?
- fprintf writes formatted values; fputs writes a plain string as it is.
Remember
- Letter (fgetc), line (fgets), form (fscanf).
- int ch, compare with EOF.
Next Topic
Next lesson: Binary Files in C. You will store whole structures in binary files with fwrite() and fread().