File operations in C: fopen, fprintf, fscanf, and fclose.
π What you'll learn on this page
β Must-know essentials
fopen(path, "r") / "w" / "a"
Always fclose
Check fp == NULL on failure
β Read if you have time
Binary mode "rb" "wb"
fprintf, fscanf, fgets
File position with fseek, ftell
The File I/O Flow
When a program exits, the values it computed are normally lost. Writing them to a file makes the data persistent.
File I/O follows three steps: (1) open (fopen) β (2) read or write (fprintf/fscanf) β (3) close (fclose).
π
(1) fopen
Open the file
β
βοΈ
(2) Read/Write
fprintf / fscanf
β
π
(3) fclose
Close the file
FILE *fp = fopen("data.txt", "w"); // "w" = write
if(fp == NULL){
printf("Could not open file\n");
return 1;
}
fprintf(fp, "Hello File!\n"); // write to the file
fclose(fp); // always close
Always check fopen's return value against NULL. If the file can't be opened (bad path, missing permissions), fopen returns NULL. Skip the check and your program will crash.
Writing to a File (fprintf)
fprintf is nearly identical to printf β it just takes a FILE pointer as its first argument.
FILE *fp = fopen("scores.txt", "w");
int scores[3] = {85, 92, 78};
for(int i = 0; i < 3; i++){
fprintf(fp, "Student%d: %d\n", i+1, scores[i]);
}
fclose(fp);
Mode "w" (write)
Creates a new file or overwrites an existing one. Any prior content is erased.
Mode "a" (append)
Appends new content at the end of an existing file.
Mode "r" (read)
Read-only. Returns NULL if the file doesn't exist.
Reading from a File (fscanf)
fscanf is the file counterpart to scanf. Check its return value to see whether the read succeeded.
fgets is safe: it takes the buffer size (via sizeof(buf)), which prevents buffer overflows β a far safer choice than scanf("%s").
π Virtual File System β See file operations in action
Watch what fopen, fgets, fputs, fseek, and fclose actually do, step by step. See the file pointer position, buffer contents, and how each mode ("r", "w", "a") behaves.
π§ͺ Pick a scenario
Pick a scenario
// No scenario selected
π data.txt contents
mode: -FILE* fp: NULLpos (ftell): -
buffer (buf): -
Operation log
(Pick a scenario and press βΆ)
π‘ Watch for: The yellow cursor (|) shows the current file pointer position. "w" empties the file on open, "a" always appends at the end, and fseek jumps to any offset.
Try It Yourself β File I/O
This example simulates writing to and reading from a file, all in your browser.