C Lesson 33 – Reading and Writing Files | Dataplexa

Reading & Writing Files in C

In the previous lesson, you learned how to read and write files character by character.

In real programs, we usually work with formatted data such as numbers, names, marks, and records.

C provides formatted file functions to handle such data easily.


Formatted File Functions

The two most commonly used formatted file functions are:

  • fprintf() – write formatted data to a file
  • fscanf() – read formatted data from a file

Writing Data Using fprintf()

fprintf() works like printf(), but writes output to a file.


#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("student.txt", "w");

    fprintf(fp, "Roll: %d\n", 101);
    fprintf(fp, "Marks: %.2f\n", 87.5);

    fclose(fp);
    return 0;
}

This program stores formatted values inside student.txt.


Reading Data Using fscanf()

fscanf() works like scanf(), but reads input from a file.


#include <stdio.h>

int main() {
    FILE *fp;
    int roll;
    float marks;

    fp = fopen("student.txt", "r");

    fscanf(fp, "Roll: %d\n", &roll);
    fscanf(fp, "Marks: %f\n", &marks);

    printf("Roll = %d\n", roll);
    printf("Marks = %.2f\n", marks);

    fclose(fp);
    return 0;
}

The data is read exactly in the same format it was written.


Important Rule

The format used in fscanf() must match the format used in fprintf().

Otherwise, incorrect data will be read.


Real-World Example: Student Record

Consider storing student details:

  • Roll number
  • Name
  • Marks

Formatted file I/O makes this simple and readable.


Appending Formatted Data


FILE *fp = fopen("student.txt", "a");
fprintf(fp, "\nRoll: %d  Marks: %.2f", 102, 91.0);
fclose(fp);

New records are added without deleting old ones.


Mini Practice

  • Create a file named employees.txt
  • Store employee id and salary using fprintf()
  • Read and display them using fscanf()

Quick Quiz

Q1. Which function writes formatted data to a file?

fprintf()

Q2. Which function reads formatted data from a file?

fscanf()

Q3. Should the format strings match while reading and writing?

Yes.

Q4. Is fprintf similar to printf?

Yes, but it writes to a file.

Q5. Can formatted file I/O be used for records?

Yes.