C reads and writes files through FILE streams: fopen chooses a mode, character, line, formatted and binary functions move the data, fseek/ftell/rewind position the stream, and fclose finishes. Modes, return values and the feof trap are favourite questions.
Medium 50 minSyllabus: “File handling”
Mark as
The idea in one minute
A file is like a long cassette tape, and a FILE pointer is the player's head. fopen loads the tape and decides whether you may play it (read), record over it (write — erasing it first) or record after the end (append). Every read or write moves the head forward; fseek fast-forwards or rewinds it to any spot, and ftell tells you where it is. fclose ejects the tape, making sure everything recorded is really saved.
Key points — the night-before list
FILE *fp = fopen(name, mode); returns NULL on failure — always check it. fclose(fp) flushes the buffer and releases the stream.
"r" needs an existing file; "w" creates or truncates to zero length; "a" creates or appends at the end; "+" adds the other direction; "b" means binary.
fgetc returns an int — a byte as unsigned char, or EOF (−1) — so store it in an int, never a char.
fgets(buf, n, fp) reads at most n − 1 characters, keeps the newline and adds '\0'; fputs adds no newline (puts does).
fprintf/fscanf do formatted text I/O; fread/fwrite move raw bytes and return the number of items, not bytes.
fseek(fp, offset, SEEK_SET | SEEK_CUR | SEEK_END) moves the position, ftell reports it, and rewind returns to the start and clears errors.
feof becomes true only after a read fails at end of file — loop on the read function's return value, not on !feof(fp).
stdin, stdout and stderr open automatically; stderr is unbuffered, so error messages appear at once.
01Streams and the FILE structure
Data held in variables disappears when a program ends; files keep it on disk. C performs all input and output through streams — sequences of bytes flowing to or from a file or device — each represented by a FILE object declared in <stdio.h>. You never touch a FILE's insides: you hold a pointer to it (FILE *fp) and pass that pointer to the library functions.
A FILE records which operating-system file it is attached to, a buffer (so that data moves in efficient blocks rather than byte by byte), the current file position, and two flags — an end-of-file indicator and an error indicator. Every program starts with three streams already open: stdin (standard input, usually the keyboard), stdout (standard output, the screen) and stderr (standard error, also the screen). printf(…) is simply fprintf(stdout, …).
Every file program follows four steps
Declare a FILE pointer
FILE *fp;
Open the file
fp = fopen("marks.txt", "r"); and check that fp is not NULL.
Read or write
Use character, line, formatted or block functions, repositioning with fseek or rewind when needed.
Close the file
fclose(fp); writes out any buffered data and releases the stream.
Buffering
Output waits in the buffer until it fills, until a newline arrives (for a line-buffered terminal), or until fflush(fp) or fclose(fp) is called. stdout is usually line-buffered on a terminal and fully buffered when redirected to a file; stderr is unbuffered so that error messages appear immediately. A program that crashes can lose buffered output that was never flushed.
02Opening and closing: the fopen modes
FILE *fopen(const char *filename, const char *mode); opens a file and returns a stream pointer — or NULL if it cannot (file missing, no permission, bad path, too many open files). The mode string decides what you may do and what happens to an existing file:
Mode
Purpose
If the file exists
If it does not exist
Starting position
"r"
read only
opened unchanged
fopen fails → NULL
start
"w"
write only
truncated to length 0 (contents lost)
created
start
"a"
append (write only)
opened unchanged
created
end — every write goes to the end
"r+"
read and write (update)
opened unchanged
fopen fails → NULL
start
"w+"
read and write
truncated to length 0
created
start
"a+"
read and append
opened unchanged
created
writes always at the end; where reading starts varies — rewind first
"rb""wb""ab""r+b"/"rb+""w+b""a+b"
the same modes for binary files
as above
as above
as above
fopen modes
A b selects binary mode: bytes pass through unchanged. In text mode a system may translate line endings — Windows stores \n as \r\n and may treat Ctrl-Z as end of file — whereas on Unix-like systems text and binary modes behave identically.
C11 added an x (exclusive) flag for the w-modes: "wx" fails if the file already exists, preventing accidental overwrites.
In the update (+) modes, a write must not be followed directly by a read without an intervening fflush, fseek, fsetpos or rewind — and a read must not be followed by a write without a positioning call — otherwise the behaviour is undefined.
int fclose(FILE *fp); flushes and closes the stream, returning 0 on success or EOF on error. Streams still open are flushed and closed when main returns or exit is called, but closing early frees the slot; at least FOPEN_MAX (minimum 8) streams can be open at once.
COpening with an error check
#include <stdio.h>#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("missing.txt", "r");
if (fp == NULL) { /* ALWAYS check */
perror("missing.txt"); /* e.g. missing.txt: No such file or directory */
return EXIT_FAILURE;
}
/* ... read the file ... */
fclose(fp);
return EXIT_SUCCESS;
}
PSC favourites
fopen returns NULL on failure — not 0, 1 or EOF, as distractors suggest. "w" destroys an existing file's contents; "a" never overwrites existing data; "r+" reads and writes without truncating, but the file must already exist.
03Character and line input/output
Function
What it does
Returns
int fgetc(FILE *fp) / getc(fp)
reads the next byte
the byte as an unsigned char converted to int, or EOF
int fputc(int c, FILE *fp) / putc(c, fp)
writes one byte
the byte written, or EOF on error
getchar() / putchar(c)
same as getc(stdin) / putc(c, stdout)
as above
char *fgets(char *buf, int n, FILE *fp)
reads a line: at most n − 1 chars, stops after '\n' (kept), adds '\0'
buf, or NULL at end of file or on error
int fputs(const char *s, FILE *fp)
writes a string without adding a newline
non-negative, or EOF on error
int puts(const char *s)
writes s to stdout and adds '\n'
non-negative, or EOF
int ungetc(int c, FILE *fp)
pushes one character back to be read again
c, or EOF
Character and line functions
fgetc returns an int, not a char, so that it can deliver every one of the 256 possible byte values and the distinct value EOF (a negative constant, −1 on all common systems). Store the result in a char and one of two things breaks: a genuine byte 0xFF is mistaken for EOF (when char is signed), or EOF is never recognised and the loop never ends (when char is unsigned).
CCopy a file byte by byte while counting characters, lines and words
#include <stdio.h>#include <ctype.h>
int main(void)
{
FILE *out = fopen("poem.txt", "w"); /* make a sample file */
if (out == NULL) { perror("poem.txt"); return 1; }
fputs("Twinkle twinkle\nlittle star\n", out);
fclose(out);
FILE *in = fopen("poem.txt", "r");
FILE *copy = fopen("poem_copy.txt", "w");
if (in == NULL || copy == NULL) { perror("fopen"); return 1; }
int c; /* int, so EOF fits */
long chars = 0, lines = 0, words = 0;
int in_word = 0;
while ((c = fgetc(in)) != EOF) {
fputc(c, copy); /* copy byte by byte */
chars++;
if (c == '\n') lines++;
if (isspace(c)) in_word = 0;
else if (!in_word) { in_word = 1; words++; }
}
fclose(in);
fclose(copy);
printf("%ld chars, %ld lines, %ld words\n", chars, lines, words);
/* 28 chars, 2 lines, 4 words */
return 0;
}
To process a file line by line, loop on fgets: while (fgets(line, sizeof line, fp) != NULL) { … }. Each line keeps its '\n' — unless the line was longer than the buffer, in which case the rest arrives in the next call — and you can strip it with line[strcspn(line, "\n")] = '\0';.
04Formatted I/O: fprintf and fscanf
fprintf(fp, format, …) and fscanf(fp, format, …) work exactly like printf and scanf, but on any stream — an easy way to store records as readable text. fscanf returns the number of items successfully assigned, or EOF if input ends before the first conversion, so a safe loop compares its result with the number of items expected. sprintf/snprintf and sscanf apply the same formats to strings instead of files.
CWriting and reading text records
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("marks.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "%d %s %.1f\n", 1, "Anu", 88.5);
fprintf(fp, "%d %s %.1f\n", 2, "Biju", 72.0);
fprintf(fp, "%d %s %.1f\n", 3, "Cini", 91.5);
fclose(fp);
fp = fopen("marks.txt", "r");
if (fp == NULL) return 1;
int roll, n = 0;
char name[20];
float marks, total = 0;
while (fscanf(fp, "%d %19s %f", &roll, name, &marks) == 3) { /* 3 items per record */
printf("%d %-5s %5.1f\n", roll, name, marks);
total += marks;
n++;
}
fclose(fp);
printf("average %.2f\n", total / n); /* average 84.00 */
fprintf(stderr, "done\n"); /* diagnostics belong on stderr */
return 0;
}
Errors go to stderr
Write error messages with fprintf(stderr, …) or perror("context"). They still reach the screen when normal output is redirected to a file (./prog > out.txt), and buffering never delays them.
05Binary I/O with fread and fwrite
Text files store numbers as characters: the int 123456 becomes six digit characters plus a separator. Binary files store bytes exactly as they sit in memory: that int takes 4 bytes, and a whole structure can be written in one call. size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp); writes count items of size bytes from ptr, and fread reads them back. Both return the number of items (not bytes) transferred — fewer than count means end of file or an error.
CWrite three records at once, then jump straight to the third
#include <stdio.h>
struct student {
int roll;
char name[16];
float marks;
};
int main(void)
{
struct student s[3] = {{1, "Anu", 88.5f}, {2, "Biju", 72.0f}, {3, "Cini", 91.5f}};
FILE *fp = fopen("students.dat", "wb");
if (fp == NULL) return 1;
size_t written = fwrite(s, sizeof s[0], 3, fp); /* all three records */
fclose(fp);
printf("wrote %zu records of %zu bytes\n", written, sizeof s[0]); /* wrote 3 records of 24 bytes */
fp = fopen("students.dat", "rb");
if (fp == NULL) return 1;
struct student r;
fseek(fp, 2 * (long)sizeof r, SEEK_SET); /* record index 2 */
if (fread(&r, sizeof r, 1, fp) == 1)
printf("%d %s %.1f\n", r.roll, r.name, r.marks); /* 3 Cini 91.5 */
fseek(fp, 0, SEEK_END);
printf("file holds %ld records\n", ftell(fp) / (long)sizeof r); /* 3 */
fclose(fp);
return 0;
}
Text file
Human-readable characters; opens in any editor
Numbers stored as digits: 123456 takes 6 bytes plus separators
Line endings may be translated (\r\n on Windows)
Portable between machines; read with fscanf or fgets
Natural for sequential access; positions are awkward
Binary file
Raw bytes copied from memory
123456 as an int always takes 4 bytes: fixed-size records
No translation — what you write is exactly what is stored
Depends on type sizes, padding and byte order, so may not move between systems
Random access is easy: record k starts at k × sizeof(record)
Record arithmetic
With fixed-size records, record number k (counting from 0) starts at byte k × sizeof(record), and the number of records = file size ÷ sizeof(record). Every 'update the 5th record' program is built on these two formulas.
06Random access: fseek, ftell and rewind
Normally a stream is read or written sequentially, the position advancing with each operation. int fseek(FILE *fp, long offset, int origin); moves the position to offset bytes from an origin: SEEK_SET (0, the beginning), SEEK_CUR (1, the current position) or SEEK_END (2, the end). It returns 0 on success and non-zero on failure, and it clears the end-of-file indicator. long ftell(FILE *fp); returns the current position — for a binary stream, the number of bytes from the beginning — or −1L on error.
Call
Moves to
fseek(fp, 0L, SEEK_SET)
the beginning (like rewind)
fseek(fp, 10L, SEEK_SET)
byte offset 10 — the 11th byte
fseek(fp, -5L, SEEK_CUR)
5 bytes back from the current position
fseek(fp, 0L, SEEK_END)
the end of the file — ftell(fp) then gives the file size
fseek(fp, -3L, SEEK_END)
3 bytes before the end
rewind(fp)
the beginning, and it also clears the error indicator; returns nothing
Common positioning calls
CTracing positions in an 11-byte file
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("hello.txt", "w+b"); /* create, write, then read back */
if (fp == NULL) return 1;
fputs("HELLO WORLD", fp); /* 11 bytes: offsets 0..10 */
fseek(fp, 6, SEEK_SET); /* a seek must separate write and read */
int c = fgetc(fp);
printf("%c %ld\n", c, ftell(fp)); /* W 7 */
fseek(fp, -3, SEEK_END);
c = fgetc(fp);
printf("%c %ld\n", c, ftell(fp)); /* R 9 */
fseek(fp, -2, SEEK_CUR);
c = fgetc(fp);
printf("%c %ld\n", c, ftell(fp)); /* O 8 */
rewind(fp);
printf("%c\n", fgetc(fp)); /* H */
fseek(fp, 0, SEEK_END);
printf("size = %ld\n", ftell(fp)); /* size = 11 */
fclose(fp);
return 0;
}
Text-mode positions and big files
For text streams the standard promises only that a value returned by ftell can be handed back to fseek with SEEK_SET; byte arithmetic on text positions is reliable only where no line-ending translation happens (Unix). Use binary mode for record arithmetic. For files beyond 2 GB a long may be too small — POSIX provides fseeko/ftello, and standard C provides fgetpos/fsetpos.
07End of file and errors: feof, ferror and the while(!feof) bug
int feof(FILE *fp) returns non-zero if the stream's end-of-file indicator is set, and int ferror(FILE *fp) does the same for its error indicator. The crucial detail: the EOF indicator is set only after a read has tried to go past the end. Reading the last byte successfully does not set it — the next read fails and sets it.
CThe classic bug and its fix
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("three.txt", "w+");
if (fp == NULL) return 1;
fputs("a\nb\nc\n", fp);
rewind(fp);
char line[32];
printf("buggy:");
while (!feof(fp)) { /* tested BEFORE the read fails */
fgets(line, sizeof line, fp); /* 4th call fails; line unchanged */
printf(" %c", line[0]);
}
printf("\n"); /* buggy: a b c c */
rewind(fp); /* also clears the EOF flag */
printf("fixed:");
while (fgets(line, sizeof line, fp) != NULL) /* test the READ itself */
printf(" %c", line[0]);
printf("\n"); /* fixed: a b c */
if (ferror(fp)) perror("three.txt"); /* error, or just end of file? */
fclose(fp);
return 0;
}
Why the last line appears twice: after the third fgets reads "c\n", the EOF indicator is still clear, so !feof(fp) lets the loop run once more. The fourth fgets hits the end, returns NULL and leaves line unchanged — and the body prints the stale "c" again. The rule: loop on the return value of the reading function (!= EOF for fgetc, != NULL for fgets, == n for fscanf and fread), and use feof and ferror only afterwards, to learn why reading stopped.
perror("msg") prints msg, a colon and a description of the most recent error (from errno), such as marks.txt: No such file or directory.
clearerr(fp) resets both the EOF and the error indicator; rewind clears them as well.
EOF is a macro for a negative int (−1 on common systems), returned by fgetc, fputc, fputs, fscanf and fclose to signal end of file or failure.
08Complete programs: copy and append
CCopy any file, text or binary — run as ./a.out poem.txt backup.txt
#include <stdio.h>#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: %s source destination\n", argv[0]);
return EXIT_FAILURE;
}
FILE *src = fopen(argv[1], "rb");
if (src == NULL) { perror(argv[1]); return EXIT_FAILURE; }
FILE *dst = fopen(argv[2], "wb");
if (dst == NULL) { perror(argv[2]); fclose(src); return EXIT_FAILURE; }
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof buf, src)) > 0) /* block-by-block copy */
if (fwrite(buf, 1, n, dst) != n) { perror("write"); break; }
fclose(src);
if (fclose(dst) == EOF) perror("close"); /* the final flush can fail too */
return EXIT_SUCCESS;
}
CAppend a record to a binary file, then list every record
#include <stdio.h>#include <string.h>
struct record {
int id;
char item[16];
int qty;
};
int main(void)
{
struct record r = {101, "", 40};
strcpy(r.item, "pencils");
FILE *fp = fopen("stock.dat", "ab"); /* create or append; never truncates */
if (fp == NULL) { perror("stock.dat"); return 1; }
fwrite(&r, sizeof r, 1, fp);
fclose(fp);
fp = fopen("stock.dat", "rb");
if (fp == NULL) { perror("stock.dat"); return 1; }
int count = 0;
while (fread(&r, sizeof r, 1, fp) == 1) /* loop on fread's result */
printf("%d. %d %s %d\n", ++count, r.id, r.item, r.qty); /* 1. 101 pencils 40 */
fclose(fp);
return 0;
}
The pattern is the same in every program: open and check, loop on the return value of the I/O function, report problems on stderr, and close every stream you opened. Binary mode (rb/wb) lets the copy program handle images and executables as well as text, and ab lets the append program run again and again, adding one record each time without disturbing the old ones.
Step through · What happens behind fopen, fprintf and fclose
step 1 / 9
Step 1: fopen("log.txt", "w")
The library allocates a FILE object with an empty buffer and asks the kernel to open the file.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Choosing the right fopen mode
Pick the mode for each task: (a) read a configuration file that must already exist; (b) write a fresh report each run, discarding the old one; (c) add lines to a log without losing earlier entries; (d) update record 5 inside an existing binary file; (e) create a new binary file, write records and read them back without reopening it.
EX 2Tracing fseek and ftell
A file contains exactly HELLO WORLD (11 bytes) and is opened with "rb". Give the character read and the ftell value after each step: fseek(fp, 6, SEEK_SET); c = fgetc(fp); then fseek(fp, -3, SEEK_END); c = fgetc(fp); then fseek(fp, -2, SEEK_CUR); c = fgetc(fp); then rewind(fp); c = fgetc(fp);
EX 3Why while(!feof(fp)) repeats the last line
A file holds three lines: a, b and c. Explain why while (!feof(fp)) { fgets(line, sizeof line, fp); printf("%s", line); } prints c twice, and correct it.
EX 4Records in a binary file
A binary file holds struct rec { int id; char name[20]; double fee; } records written with fwrite on a 64-bit system, and the file is 640 bytes long. How many records does it hold, at which byte does the 7th record (counting from 1) start, and which calls read that record?
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
From the mode table: (a) which modes create a file that does not exist? (b) Which modes destroy an existing file's contents? (c) Which mode opens an existing file for reading and writing without erasing it? (d) In which modes can existing data never be overwritten?
Q2
Write a program that counts the lines of a text file named on the command line. What would a version that only counts '\n' characters report for a file whose last line has no newline, and how do you count that line too?
Q3
A 100-byte file is opened with "rb". What does printf("%ld", ftell(fp)) print after fseek(fp, 20, SEEK_SET); fseek(fp, 30, SEEK_CUR); fseek(fp, -10, SEEK_CUR); — and after a further fseek(fp, -25, SEEK_END);?
Q4
Why must c be an int in while ((c = fgetc(fp)) != EOF)? Describe what goes wrong if c is a char, for both signed and unsigned char.
Q5
The file students.dat holds 3 records of struct student { int roll; char name[16]; float marks; } written with fwrite (as in the binary I/O section). Write code that changes the marks of the record with roll 2 to 80.0 in place, without rewriting the other records.
Exam traps
fopen returns NULL (not 0, −1 or EOF) on failure — check it before using the pointer.
"w" and "w+" erase an existing file; "r+" keeps the contents but fails if the file is missing; in "a" mode every write goes to the end, even after fseek.
feof() turns true only after a read has failed, so while (!feof(fp)) processes the last item twice — loop on the read function's return value.
fgetc returns an int; storing it in a char breaks the EOF test.
fgets keeps the '\n' and reads at most n − 1 characters; puts adds a newline but fputs does not; fread and fwrite return item counts, not bytes.
In the update (+) modes a read may not directly follow a write, or a write a read, without fflush, fseek or rewind in between.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
File handling in C · Question 1 of 10✓ 0 · ✗ 0
If fopen() cannot open the requested file, it returns:
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 2✓ 0 · ✗ 0
Modelled on QP 105/2024 · Higher Secondary School Teacher (Junior) Computer Science (8 Aug 2024), Q.24 (reworded)original paper (PDF)