File Management
Open in the Padhaiko app9.1 Introduction
Variables, arrays, and structures stored in RAM are volatile: their contents disappear as soon as the program terminates or power is lost. A file is a named collection of related bytes stored persistently on secondary storage (HDD, SSD, USB drive).
In C, file handling through <stdio.h> lets programs store large datasets permanently, share results across separate runs or programs, and process data larger than main memory via buffered streams.
9.2 Binary and text file in C
Every file in C is accessed as either a text stream or a binary stream.
| Aspect | Text File (.txt, .csv) | Binary File (.bin, .dat) |
|---|---|---|
| Data Representation | Stored as human-readable ASCII/UTF-8 character codes (e.g., integer 1234 takes 4 characters '1','2','3','4') | Stored in exact raw internal memory bit format (e.g., int 1234 takes fixed 4 bytes sizeof(int)) |
| Newline Translation | On Windows, '\n' may translate to '\r\n' on write and back to '\n' on read | No character translation; every byte 0x00–0xFF is written and read verbatim |
| Readability & Portability | Directly readable/editable in any text editor; portable across CPUs | Not human-readable; faster, more compact for numbers/structs, dependent on byte endianness |
| Typical I/O Functions | fgetc(), fputc(), fgets(), fputs(), fprintf(), fscanf() | fread(), fwrite() |
9.3 File opening modes
When opening a file with fopen(filename, mode), the mode string specifies whether the file is opened for reading, writing, or appending, and whether it is text or binary (append b for binary modes: "rb", "wb", "ab", "r+b", "w+b", "a+b").
| Mode | Meaning | If File Exists | If File Does Not Exist |
|---|---|---|---|
"r" | Read text only | Opens at start for reading | Fails and returns NULL |
"w" | Write text only | Truncates (erases) contents to zero length | Creates a new empty file |
"a" | Append text only | Opens and writes only at the end (preserves existing data) | Creates a new empty file |
"r+" | Read and write (update) | Opens at start without erasing | Fails and returns NULL |
"w+" | Write and read | Truncates existing contents to zero | Creates a new empty file |
"a+" | Read and append | Opens for reading anywhere; all writes append to end | Creates a new empty file |
9.4 Defining, opening and closing file
All high-level file I/O in C operates through a file pointer of type FILE * (defined in <stdio.h>), which tracks the OS file descriptor, current buffer position, and EOF/error flags.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error: could not open file.\n");
return 1;
}
fprintf(fp, "Institute of Engineering ENCT 101\n");
fclose(fp);
return 0;
}fopen(const char *path, const char *mode): Opens the file and returns aFILE *, orNULLif opening fails. Always checkif (fp == NULL)before reading or writing!fclose(FILE *fp): Flushes any buffered output data to disk, releases OS file handles, and prevents data loss or resource leaks.
9.5 Input-output operations on files
9.5.1 Character I/O (fputc(), fgetc())
int fputc(int ch, FILE *fp);writes a single characterchtofp(returns the written character, orEOFon error).int fgetc(FILE *fp);reads the next single character fromfpas anunsigned charcast toint, returningEOFat end-of-file or error. Always storefgetc()in anintvariable.
9.5.2 String I/O (fgets(), fputs())
char *fgets(char *str, int n, FILE *fp);reads at mostn - 1characters until a newline'\n'orEOF, appends'\0', and returnsstr(orNULLatEOF).int fputs(const char *str, FILE *fp);writes the null-terminated stringstrtofpwithout automatically appending'\n'.
9.5.3 Formatted I/O (fscanf(), fprintf())
int fprintf(FILE *fp, const char *format, ...);works identically toprintf(), writing formatted text to the file streamfp.int fscanf(FILE *fp, const char *format, ...);works identically toscanf(), parsing formatted tokens fromfpand returning the number of successfully matched items (orEOF).
9.5.4 Record I/O (fwrite(), fread())
Used primarily with binary files to read or write entire structures or arrays directly as fixed-size byte blocks:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);Writescountrecords, each ofsizebytes, starting from memory addressptr. Returns the number of records actually written.size_t fread(void *ptr, size_t size, size_t count, FILE *fp);Reads up tocountrecords, each ofsizebytes, into memory atptr. Returns the number of full records read (fewer thancountwhenEOFor an error occurs).
9.6 Overview of random file access
In sequential access, bytes are read or written from start to finish. Random access jumps directly to any byte offset inside a file using three <stdio.h> positioning functions:
| Function | Signature / Syntax | Purpose |
|---|---|---|
fseek() | int fseek(FILE *fp, long offset, int origin); | Moves the file position indicator offset bytes relative to origin: SEEK_SET (0, file start), SEEK_CUR (1, current position), or SEEK_END (2, file end) |
ftell() | long ftell(FILE *fp); | Returns the current byte offset from the start of the file (useful to compute file size after fseek(fp, 0, SEEK_END)) |
rewind() | void rewind(FILE *fp); | Resets the file position back to byte 0 (beginning) and clears the error/EOF flags |
For example, to jump directly to the 4th record (0-based index 3) of struct Student: fseek(fp, 3L * sizeof(struct Student), SEEK_SET);
9.7 Error handling
File operations can fail due to missing files, permission errors, full disks, or reaching end-of-file unexpectedly. C provides dedicated error-checking helpers in <stdio.h>:
NULLcheck onfopen(): Always verifyfp != NULLimmediately afterfopen().int feof(FILE *fp);returns non-zero only after a read attempt hits end-of-file (do not writewhile (!feof(fp))before reading, as it executes one extra phantom iteration after the last valid record!).int ferror(FILE *fp);returns non-zero if a read/write hardware or stream error occurred onfp.void clearerr(FILE *fp);clears both the EOF and error indicators onfp.void perror(const char *msg);printsmsg: <system error message>tostderrbased on the globalerrnocode (<errno.h>).
Worked Examples
1
Write a complete C program that copies the contents of "source.txt" to "dest.txt" character by character using fgetc() and fputc(), handling open errors properly with perror().
Opening Both Streams Safely: Open "source.txt" in "r" mode and "dest.txt" in "w" mode. If either fopen() returns NULL, report the OS reason using perror(), close any already-opened stream, and return non-zero.
Character Copy Loop with int ch: Store fgetc(src) in an int (not char) and loop while ((ch = fgetc(src)) != EOF) so EOF is detected cleanly without misinterpreting valid bytes.
#include <stdio.h>
int main(void) {
FILE *src = fopen("source.txt", "r");
if (src == NULL) {
perror("Cannot open source.txt");
return 1;
}
FILE *dst = fopen("dest.txt", "w");
if (dst == NULL) {
perror("Cannot open dest.txt");
fclose(src);
return 1;
}
int ch;
while ((ch = fgetc(src)) != EOF) {
fputc(ch, dst);
}
if (ferror(src) || ferror(dst)) {
printf("I/O error during file copy.\n");
}
fclose(src);
fclose(dst);
return 0;
}Open "source.txt" with "r" and "dest.txt" with "w", check both against NULL, copy with int ch; while ((ch = fgetc(src)) != EOF) fputc(ch, dst);, check ferror(), and close both files with fclose().
2
A binary file "students.dat" stores 4 records of struct Student where sizeof(struct Student) = 40 bytes. Write a C snippet using fwrite(), fseek(), ftell(), and fread() to:
- Find the total file size in bytes.
- Jump directly to the 3rd student record (1-based: 3rd record, index
2) and read it intostruct Student s.
Compute the exact byte offset passed to fseek() and total file size.
Computing File Size with fseek() and ftell(): Seeking to the end with fseek(fp, 0L, SEEK_END); places the indicator at byte 4 * 40 = 160. Calling long sz = ftell(fp); returns 160 bytes.
Random Access to Record 3:
FILE *fp = fopen("students.dat", "rb");
if (fp != NULL) {
fseek(fp, 0L, SEEK_END);
long total_bytes = ftell(fp); /* 160 bytes */
struct Student s;
fseek(fp, 2L * sizeof(struct Student), SEEK_SET); /* offset = 80 */
fread(&s, sizeof(struct Student), 1, fp);
printf("Size=%ld\n", total_bytes);
fclose(fp);
}- Total file size returned by
ftell(): 160 bytes (4 * 40). - Byte offset for the 3rd record (
index = 2): 80 bytes (2 * 40), usingfseek(fp, 2L * sizeof(struct Student), SEEK_SET);.
3
Write a C program using fprintf() and fscanf() to write 3 student records (roll and marks) into "marks.txt", reopen the file for reading, compute their average marks, and avoid the while (!feof(fp)) pitfall.
Writing with fprintf() and Reading Safely with fscanf(): Instead of while (!feof(fp)), use the return value of fscanf() directly as the loop condition (while (fscanf(fp, "%d %d", &roll, &marks) == 2)), which stops immediately when EOF is reached and never processes a duplicate final line.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("marks.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "101 85\n102 92\n103 78\n");
fclose(fp);
fp = fopen("marks.txt", "r");
if (fp == NULL) return 1;
int roll, m, sum = 0, count = 0;
while (fscanf(fp, "%d %d", &roll, &m) == 2) {
sum += m;
count++;
}
if (count > 0) {
printf("Average = %.2f\n", (double)sum / count);
}
fclose(fp);
return 0;
}For {85, 92, 78}, the program computes sum = 255, count = 3, and prints Average = 85.00.
Exercises
Exercises — File Management
Differentiate between text files and binary files in C across data storage format, readability, newline handling, and I/O functions used.
Four Comparison Criteria:
- Storage Format: Text files encode numbers and strings as human-readable ASCII characters; binary files write raw memory bit patterns directly.
- Readability: Text files open cleanly in text editors; binary files appear as non-readable bytes.
- Newline Translation: Text mode translates
'\n'to platform line endings (e.g.,'\r\n'on Windows), whereas binary mode writes every byte verbatim without translation. - I/O Functions: Text files use
fgetc,fgets,fprintf,fscanf; binary files usefreadandfwrite.
Text files store human-readable ASCII characters with platform newline translation using fprintf/fscanf/fgets, whereas binary files store exact raw memory bytes without translation using fread/fwrite.
Compare the file opening modes "r", "w", "a", "r+", "w+", and "a+", clearly highlighting what happens when the file already exists versus when it does not exist.
Behavior of the Six Text Modes:
"r": Read only; fails (NULL) if missing; preserves existing file."w": Write only; creates if missing; erases/truncates existing content to 0 bytes."a": Append only; creates if missing; preserves existing data and writes only at the end."r+": Read + write; fails (NULL) if missing; preserves existing content and starts at byte 0."w+": Read + write; creates if missing; truncates existing file to 0 bytes."a+": Read + append; creates if missing; reads anywhere, writes always at end.
"r" and "r+" require the file to exist (return NULL otherwise); "w" and "w+" create missing files and truncate existing ones; "a" and "a+" create missing files and preserve existing contents by writing only at the end.
Explain the purpose of fseek(), ftell(), and rewind(). If a binary file "emp.bin" holds 5 employee structures of 64 bytes each, what byte offset does fseek() use to jump to the 5th (last) record from SEEK_SET, and what does ftell() return after fseek(fp, 0L, SEEK_END)?
Random Access Functions:
fseek(fp, offset, origin)moves the file pointer relative toSEEK_SET,SEEK_CUR, orSEEK_END.ftell(fp)returns the current byte offset from the start of the file.rewind(fp)resets the pointer to byte0and clears EOF/error flags.
Byte Calculations (sizeof(emp) = 64):
- 5th record (0-based index
4) starts at4 * 64 = 256bytes fromSEEK_SET. - After
fseek(fp, 0L, SEEK_END),ftell(fp)returns total file size:5 * 64 = 320bytes.
fseek() repositions the file cursor, ftell() returns the current byte offset, and rewind() resets to byte 0. Offset to the 5th record = 256 bytes (4 * 64); ftell() at EOF = 320 bytes (5 * 64).
Write the function prototypes and roles of fread() and fwrite(). What does fread() return, and how do you verify that a record write or read succeeded?
Signatures and Parameters:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
Here ptr is the memory buffer address, size is bytes per item (sizeof(struct ...)), count is the number of items, and fp is the binary FILE *.
Return Value Verification: Both return the size_t count of complete items successfully transferred. Comparing the return value against count (for instance, if (fread(&rec, sizeof(rec), 1, fp) == 1)) confirms a full record was read; if fewer items return, check feof(fp) vs. ferror(fp).
fwrite()/fread() transfer count binary blocks of size bytes between buffer ptr and fp, returning the number of complete records transferred. Success is verified when the returned count equals the requested count.
Why is while (!feof(fp)) considered a bug-prone idiom in C file reading loops, and how do ferror() and perror() help handle file I/O errors?
Why while (!feof(fp)) Fails: feof(fp) only becomes true after a read function tries to read past the end of the file and fails. Testing !feof(fp) before reading enters the loop one extra time after the last valid item, causing fscanf/fread to fail while the body processes stale data from the previous iteration. Instead, check the read call itself (while (fscanf(...) == N) or while (fgets(...) != NULL)).
Using ferror() and perror():
ferror(fp)distinguishes a true I/O failure from normalEOFafter a read loop ends.perror("msg")prints the programmer's prefix followed by the OS error description (errno) tostderr.
feof(fp) triggers only after a failed read past EOF, so while (!feof(fp)) causes an extra bogus iteration; check the read function's return value directly instead. Use ferror(fp) to detect hardware/stream failures and perror() to print human-readable OS error messages.