fprintf and fscanf
- C course
- Intermediate
- Lesson 48/116
- 5 min
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.
Practice 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);.
Starter code
#include <stdio.h>
// Open data.txt with fopen (write mode)
// Write 25 and "Ayşe" with fprintf
// fclose, then reopen in read mode
// Read with fscanf, print with printf
int main(void) {
return 0;
}Sample 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;
}Expected output
25 Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match functions to purpose
| Term | Meaning |
|---|---|
fprintf(f, ...) |
Write to file |
fscanf(f, ...) |
Read from file |
%d |
Integer format |
%s |
String format |
2 Which function reads an int from a file?
- scanf
- fscanf(f, "%d", &x) Correct answer
- fgets
- fgetc
Explanation: fscanf reads formatted data from a file via FILE*.
3 Complete the fscanf call
fscanf(f, "%d", &____);
fscanf(f, "%d", &age);
Explanation: &age gives the address of the age variable.