File operations in C: fopen, fprintf, fscanf, and fclose.
π What to 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. Saving them to a file makes the data persistent.
File I/O takes three steps: (1) open (fopen) β (2) read/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 cannot be opened (bad path, missing permissions), fopen returns NULL. Without the check, the program will crash.
Writing to a File (fprintf)
fprintf is almost identical to printf, except the first argument is a FILE pointer.
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)
Create new, or overwrite. Existing content is erased.
Mode "a" (append)
Append mode. Writes at the end of the existing file.
Mode "r" (read)
Read-only. Returns NULL if the file does not exist.
Reading from a File (fscanf)
fscanf is the file version of scanf. Use its return value to tell whether the read succeeded.