Back to course

File I/O Part 5: Formatted I/O (fprintf, fscanf)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 51: File I/O Part 5: Formatted I/O (fprintf, fscanf)

These functions are the file stream equivalents of printf and scanf, allowing you to read and write formatted data (integers, floats, formatted strings) easily.

Writing Formatted Data: fprintf()

Writes formatted output to the specified stream.

Syntax: int fprintf(FILE *stream, const char *format, ...);

c #include <stdio.h>

struct Data { int id; float amount; }; struct Data record = {123, 50.75};

FILE *fp = fopen("records.txt", "w");

if (fp != NULL) { // Writing structured data separated by commas fprintf(fp, "ID: %d, Amount: %.2f\n", record.id, record.amount); fclose(fp); }

Reading Formatted Data: fscanf()

Reads formatted input from the specified stream.

Syntax: int fscanf(FILE *stream, const char *format, ...);

Crucial Reminder: Like scanf, fscanf requires the addresses (&) of variables to store the data.

c FILE *fp = fopen("records.txt", "r"); int read_id; float read_amount;

if (fp != NULL) { // Need to match the expected format exactly (e.g., skip 'ID: ', comma, etc.) int items_read = fscanf(fp, "ID: %d, Amount: %f\n", &read_id, &read_amount);

if (items_read == 2) {
    printf("Successfully read ID %d and Amount %.2f\n", read_id, read_amount);
}
fclose(fp);

}

Limitation: fscanf is sensitive to format changes (e.g., extra spaces or missing separators) and is generally poor at handling lines containing strings with spaces, making it less robust than fgets for general text file reading.