C
fprintf and fscanf
Learn to write and read files with fprintf and fscanf.
fprintf and fscanf
fprintf and fscanf are the basic way to write and read formatted data to/from a file. They work like printf and scanf; the difference is they take a FILE* as the first parameter.
Example: fprintf(f, "%d %s\n", 25, "Ayşe"); writes 25 Ayşe to the file. fscanf(f, "%d %s", &age, name); reads an int and a string from the file. Format specifiers (%d, %s, %f) are the same as printf/scanf. In fscanf, integers need & (address); strings don't because a string name is already a pointer.
Address operator
When reading an integer with fscanf, the & (address) operator is required. Because fscanf writes the value into the variable via its address. Strings don't need &.
Example: int age; fscanf(f, "%d", &age);. Here &age is the address of age. fscanf writes the read value to this address. But char name[32]; fscanf(f, "%s", name); has no &; because name is already the array's start address. This distinction is the foundation of the pointer-array relationship in C; forgetting it triggers a compiler warning.
Exercise Write data, read back and print
Open with FILE *f = fopen("data.txt", "w"); (check NULL). Write with fprintf(f, "%d %s\n", 25, "Ayşe");, fclose(f);. Reopen with f = fopen("data.txt", "r");. Declare int age; char name[32];; read with fscanf(f, "%d %31s", &age, name);. fclose(f);. Print with printf("%d %s\n", age, name);.
Show example solution
#include <stdio.h>
int main(void) {
FILE *f = fopen("data.txt", "w");
if (f == NULL) return 1;
fprintf(f, "%d %s\n", 25, "Ayşe");
fclose(f);
f = fopen("data.txt", "r");
if (f == NULL) return 1;
int age;
char name[32];
fscanf(f, "%d %31s", &age, name);
fclose(f);
printf("%d %s\n", age, name);
return 0;
}
Test yourself
-
Match functions to purpose
- fprintf(f, ...)
- Write to file
- fscanf(f, ...)
- Read from file
- %d
- Integer format
- %s
- String format
-
Which function reads an int from a file?
- scanf
- fscanf(f, "%d", &x)
- fgets
- fgetc
Show answer
fscanf(f, "%d", &x) — fscanf reads formatted data from a file via FILE*.
-
Complete the fscanf call
fscanf(f, "%d", &____);
Show answer
fscanf(f, "%d", &age);
Next lesson: fgets and fputs