› Module 11: File Handling › 11.2 Reading and Writing Functions
M O D U L E

Module 11: File Handling

Reading from and writing to files on disk, so data can persist beyond a single program run.

11.1 File Basics: fopen(), Modes, and fclose()

FILE *fp = fopen("name.txt", "mode") opens a file and returns a pointer used for all subsequent operations on it (or NULL if it fails, e.g. file not found). Common modes: "r" read, "w" write (creates/overwrites), "a" append, "r+" read & write. fclose(fp) must be called when finished — it flushes any buffered data to disk and releases the file handle.

FILE *fp = fopen("data.txt","w"); fprintf(fp, ...); fputs(...); Data written to data.txt fclose(fp); // flushes & closes file
Opening, writing to, and closing a file.

11.2 Reading and Writing Functions

fprintf/fscanf work like printf/scanf but target a file instead of the console. fputs/fgets write and read whole lines of text. fread/fwrite handle raw binary data in fixed-size blocks — used for structs, images, or any non-text data — and are typically paired with sizeof() to specify block size.

Function Use
fprintf(fp, fmt, ...)Write formatted text to a file
fscanf(fp, fmt, ...)Read formatted text from a file
fgets(buf, n, fp)Read up to n-1 characters or one line
fwrite(ptr,size,n,fp)Write raw binary data
fread(ptr,size,n,fp)Read raw binary data
MODULE COMPREHENSIVE QUIZ

Module 11 Final Quiz

Test your understanding across all 2 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 11 Final Quiz →
Yukti Mascot