← Back to C Course | Chapter 10: File I/O | Lesson 4 of 6

C fprintf() & fscanf()

Writing formatted text with fprintf()

This means all the same format specifiers you use with printf() (%d, %s, %f, and so on) work identically with fprintf(), just directed at a file stream instead of the console -- useful for generating human-readable log files or reports.

Example: Writing formatted text with fprintf()

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "Age: %d", 25);
	fclose(fp);
	printf("Formatted text written to file");
	return 0;
}

Reading formatted text with fscanf()

fscanf() uses the same %d, %s, %f format specifiers as scanf(), and like scanf(), it requires addresses (using &) for non-string variables to know where to store what it reads.

Example: Reading formatted text with fscanf()

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "%d", 42);
	fclose(fp);
	int value;
	fp = fopen("data.txt", "r");
	fscanf(fp, "%d", &value);
	fclose(fp);
	printf("%d", value);
	return 0;
}

Working with mixed data types

For example, you might write a CSV-style line with fprintf(fp, "%s,%d,%.2f\n", name, age, gpa) and later parse it back with a matching fscanf() call using the same format string structure.

Example: Working with mixed data types

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("data.csv", "w");
	fprintf(fp, "%s,%d,%.2f\n", "Alice", 20, 3.5);
	fclose(fp);
	char name[20];
	int age;
	float gpa;
	fp = fopen("data.csv", "r");
	fscanf(fp, "%[^,],%d,%f", name, &age, &gpa);
	fclose(fp);
	printf("%s %d %.2f", name, age, gpa);
	return 0;
}

Appending data with fprintf()

Because a mode positions the file pointer at the end before any writes happen, repeated fprintf() calls across multiple program runs build up a growing log file rather than overwriting previous entries each time.

Example: Appending data with fprintf()

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("log.txt", "w");
	fprintf(fp, "First entry\n");
	fclose(fp);
	fp = fopen("log.txt", "a");
	fprintf(fp, "Second entry\n");
	fclose(fp);
	printf("Log grows across runs");
	return 0;
}

Handling EOF in fscanf()

fscanf() returns the number of items it successfully matched and assigned, and this drops below your expected count (or hits EOF entirely) once there's no more data left to read -- checking this is how you detect the end of variable-length input.

Example: Handling EOF in fscanf()

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "5");
	fclose(fp);
	int value;
	fp = fopen("data.txt", "r");
	int result = fscanf(fp, "%d", &value);
	fclose(fp);
	printf("%d", result == 1);
	return 0;
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.