C Programming - Beginner to Brilliance / File Handling in C

Reading/Writing Text and Binary Files

πŸ“„ Difference Between Text and Binary Files

Feature

Text Files ("r", "w", etc.)

Binary Files ("rb", "wb", etc.)

Format

Human-readable (ASCII characters)

Non-human-readable (raw bytes)

Size

Slightly larger (extra formatting)

Smaller (raw representation)

Precision (how accurately numeric data is stored and retrieved)

Loss of precision possible

No loss of precision

Tools to Open

Any text editor (Notepad, Vim)

Specialized programs or custom readers

Use Cases

Configs, logs, user input

Images, audio, structs, serialized data


πŸ“ Text File I/O: Reading & Writing

✍️ Writing to a Text File

FILE *fp = fopen("D:\\Mrigank Programs\\C Programs\\textfile.txt", "w");
if (fp == NULL) {
    printf("Error opening file.\\n");
    return 1;
}

fprintf(fp, "Name: %s\\nAge: %d\\n", "CodeVeda", 25);
fputs("This is a simple line.\\n", fp);
fclose(fp);

πŸ—‚οΈ File: textfile.txt (before writing)

πŸ—‚οΈ File: textfile.txt (after writing)


πŸ“– Reading from a Text File

FILE *fp = fopen("D:\\Mrigank Programs\\C Programs\\textfile.txt", "r");
char line[100];

while (fgets(line, sizeof(line), fp) != NULL) {
    printf("%s", line);  // Print each line
}
fclose(fp);

πŸ” Text File Functions Recap:

Function

Purpose

fprintf()

Print formatted data

fscanf()

Read formatted data

fgets()

Read a line from file

fputs()

Write a string

fgetc()

Read one character

fputc()

Write one character


🧱 Binary File I/O: Reading & Writing

Binary files store data as raw bytes. Useful when:

  • You work with struct, images, executables.

  • Performance and precision matter.


✍️ Writing to a Binary File with fwrite()

#include <stdio.h>

struct Student {
    int id;
    float marks;
};

int main() {
    FILE *fp = fopen("student.dat", "wb");
    struct Student s1 = {1, 89.5};

    if (fp == NULL) {
        printf("Error creating binary file.\\n");
        return 1;
    }

    fwrite(&s1, sizeof(s1), 1, fp);
    fclose(fp);

    return 0;
}

πŸ“– Reading from a Binary File with fread()

#include <stdio.h>

struct Student {
    int id;
    float marks;
};

int main() {
    FILE *fp = fopen("student.dat", "rb");
    struct Student s2;

    if (fp == NULL) {
        printf("Error opening binary file.\\n");
        return 1;
    }

    fread(&s2, sizeof(s2), 1, fp);
    printf("ID: %d, Marks: %.2f\\n", s2.id, s2.marks);
    fclose(fp);

    return 0;
}

🧠 fread() vs fwrite() – Breakdown

fwrite(&data, size_of_data, count, file_pointer);
fread(&data, size_of_data, count, file_pointer);
  • size_of_data = sizeof(variable or structure)

  • count = number of items to write or read

  • Used for arrays of structures, binary formats, etc.


🧭 Binary File Use Case – Array of Structures

struct Employee emp[2] = { {1, "John"}, {2, "Doe"} };
fwrite(emp, sizeof(struct Employee), 2, fp);

To read them:

fread(emp, sizeof(struct Employee), 2, fp);

πŸ› οΈ File Modes Summary (Text vs Binary)

Mode

Meaning

"r"

Read text

"w"

Write text (overwrite)

"a"

Append text

"rb"

Read binary

"wb"

Write binary

"ab"

Append binary

"r+"

Read + Write (text)

"rb+"

Read + Write (binary)


πŸ“„ Text vs Binary File Methods in C

Operation

Text File Functions

Binary File Functions

Open File

fopen("file.txt", "r") / "w" / "a"

fopen("file.bin", "rb") / "wb" / "ab"

Write One Char

fputc('A', fp);

fputc('A', fp);

Read One Char

fgetc(fp);

fgetc(fp);

Write String

fputs("Hello", fp);

N/A (write as raw bytes)

Read String

fgets(str, size, fp);

N/A

Formatted Write

fprintf(fp, "Age: %d", age);

N/A

Formatted Read

fscanf(fp, "%d", &age);

N/A

Write Raw Data

N/A

fwrite(&var, sizeof(var), 1, fp);

Read Raw Data

N/A

fread(&var, sizeof(var), 1, fp);

Close File

fclose(fp);

fclose(fp);


🚫 Common Mistakes in File I/O

❌ Mistake

πŸ’‘ Correction

Not checking if fopen() returned NULL

Always check if the file opened successfully

Writing text with fwrite()

Use fprintf() instead

Forgetting to fclose()

Always close your files

Using "r" on non-existent file

Use "w" or check if file exists

Writing structs with padding

Use #pragma pack(1) or read/write fields individually