SrcForge

Lesson 27

File I/O

File I/O in C is the process of reading data from files and writing data to files using functions from <stdio.h>. Files allow data to be stored permanently and retrieved later, managed through the FILE data type and functions such as fopen(), fclose(), fprintf(), fscanf(), fread(), and fwrite().

C Track

Save progress as you learn.

44 lessons

Lesson content

File I/O in C Programming: A Complete Beginner to Advanced Guide

What is File I/O in C Programming?

File I/O (Input/Output) is the process of reading data from files and writing data to files. Instead of storing information only in memory while a program runs, files allow data to be saved permanently so it can be used later.

For example, a student management system can save student records to a file and retrieve them the next time the program is executed.

Think of a file as a notebook. You can write information into it, close it, and read it again whenever you need it.

Why Does File I/O Exist?

Variables and arrays store data only while a program is running. Once the program ends, that data is lost. File I/O helps to:

  • Store data permanently
  • Read previously saved data
  • Share data between programs
  • Process large amounts of information
  • Create reports and logs

Real-World Use Cases

File I/O is widely used in:

  • Student management systems
  • Banking applications
  • Inventory management
  • Log files
  • Configuration files
  • Database systems
  • Report generation
  • Game save files

Prerequisites

Before learning File I/O in C Programming, you should understand:

  • Variables
  • Data types
  • Strings
  • Functions
  • Pointers
  • Structures
  • Error handling

Core Concepts of File I/O in C Programming

What is a File?

A file is a collection of data stored on secondary storage devices such as hard drives or SSDs. In C, files are handled using a pointer of type FILE.

FILE *file;

The FILE type is defined in the <stdio.h> header file.

File Opening Modes

The fopen() function opens a file.

Syntax

FILE *fopen(const char *filename, const char *mode);

Common File Modes

ModeDescription
"r"Open an existing file for reading
"w"Open a file for writing (creates a new file or overwrites an existing one)
"a"Open a file for appending (adds data to the end)
"r+"Open a file for reading and writing
"w+"Open a file for reading and writing (overwrites existing content)
"a+"Open a file for reading and appending
"rb"Open a binary file for reading
"wb"Open a binary file for writing
"ab"Open a binary file for appending

Closing a File

Always close a file after use.

Syntax

fclose(file);

Closing a file ensures that buffered data is written to disk and system resources are released.

Text File Functions

FunctionPurpose
fprintf()Write formatted data
fscanf()Read formatted data
fgets()Read a line
fputs()Write a string
fgetc()Read one character
fputc()Write one character

Binary File Functions

FunctionPurpose
fread()Read binary data
fwrite()Write binary data

Binary files are often more efficient for storing structures and other non-text data.

File Pointer

A file pointer keeps track of the current position within a file.

FILE *file = fopen("data.txt", "r");

If the file cannot be opened, fopen() returns NULL.

Code Examples

Example 1: Beginner – Write to a File Using fprintf()

#include <stdio.h>                                  // Include standard input/output library

int main(void)                                      // Program entry point
{
    FILE *file = fopen("data.txt", "w");            // Open the file for writing

    if (file == NULL)                               // Check whether the file opened successfully
    {
        printf("Unable to open the file.\n");       // Print an error message

        return 1;                                   // Exit with an error code
    }

    fprintf(file, "Hello, C Programming!\n");       // Write text to the file

    fclose(file);                                   // Close the file

    printf("Data written successfully.\n");         // Print a success message

    return 0;                                       // End the program
}

Example 2: Beginner – Read from a File Using fgets()

#include <stdio.h>                                  // Include standard input/output library

int main(void)                                      // Program entry point
{
    char text[100];                                 // Declare a buffer for reading

    FILE *file = fopen("data.txt", "r");            // Open the file for reading

    if (file == NULL)                               // Check whether the file opened successfully
    {
        printf("Unable to open the file.\n");       // Print an error message

        return 1;                                   // Exit with an error code
    }

    fgets(text, sizeof(text), file);                // Read one line from the file

    printf("%s", text);                             // Display the line

    fclose(file);                                   // Close the file

    return 0;                                       // End the program
}

Example 3: Intermediate – Append Data to a File

#include <stdio.h>                                  // Include standard input/output library

int main(void)                                      // Program entry point
{
    FILE *file = fopen("log.txt", "a");             // Open the file in append mode

    if (file == NULL)                               // Check whether the file opened successfully
    {
        printf("Unable to open the file.\n");       // Print an error message

        return 1;                                   // Exit with an error code
    }

    fputs("Program executed successfully.\n", file); // Append a message to the file

    fclose(file);                                   // Close the file

    return 0;                                       // End the program
}

Example 4: Intermediate – Read and Write a Structure

#include <stdio.h>                                  // Include standard input/output library
#include <stdlib.h>                                 // Include standard library

struct Student                                      // Define a structure
{
    int rollNo;                                     // Student roll number

    float marks;                                    // Student marks
};

int main(void)                                      // Program entry point
{
    struct Student student = {101, 95.5f};          // Initialize a structure

    FILE *file = fopen("student.dat", "wb");        // Open a binary file for writing

    if (file == NULL)                               // Check whether the file opened successfully
    {
        printf("Unable to open the file.\n");       // Print an error message

        return 1;                                   // Exit with an error code
    }

    fwrite(&student, sizeof(struct Student), 1, file); // Write the structure

    fclose(file);                                   // Close the file

    file = fopen("student.dat", "rb");              // Reopen the file for reading

    if (file == NULL)                               // Check whether the file opened successfully
    {
        printf("Unable to open the file.\n");       // Print an error message

        return 1;                                   // Exit with an error code
    }

    struct Student record;                          // Declare another structure

    fread(&record, sizeof(struct Student), 1, file); // Read the structure

    printf("Roll No: %d\n", record.rollNo);         // Print the roll number

    printf("Marks: %.1f\n", record.marks);          // Print the marks

    fclose(file);                                   // Close the file

    return 0;                                       // End the program
}

Example 5: Advanced – Copy One File to Another

#include <stdio.h>                                  // Include standard input/output library

int main(void)                                      // Program entry point
{
    char character;                                 // Store one character

    FILE *source = fopen("input.txt", "r");         // Open the source file

    if (source == NULL)                             // Check whether the source file opened successfully
    {
        printf("Unable to open source file.\n");    // Print an error message

        return 1;                                   // Exit with an error code
    }

    FILE *destination = fopen("output.txt", "w");   // Open the destination file

    if (destination == NULL)                        // Check whether the destination file opened successfully
    {
        fclose(source);                             // Close the source file

        printf("Unable to create destination file.\n"); // Print an error message

        return 1;                                   // Exit with an error code
    }

    while ((character = fgetc(source)) != EOF)      // Read until the end of the file
    {
        fputc(character, destination);              // Write each character
    }

    fclose(source);                                 // Close the source file

    fclose(destination);                            // Close the destination file

    printf("File copied successfully.\n");          // Print a success message

    return 0;                                       // End the program
}

Common Mistakes and Pitfalls

WrongCorrect
Forgetting to check if fopen() returned NULLAlways verify that the file was opened successfully
Not calling fclose()Always close files after use
Opening a file in the wrong modeChoose the correct mode ("r", "w", "a", etc.)
Assuming fread() or fwrite() always succeedsCheck the return value
Reading beyond the end of a fileCheck for EOF or verify the number of items read

Wrong:

FILE *file = fopen("data.txt", "r");

fprintf(file, "Hello");

Correct:

FILE *file = fopen("data.txt", "r");

if (file != NULL)
{
    /* Read from the file instead of writing, or reopen it in "w"/"a" mode. */
    fclose(file);
}

Best Practices

  • Always check whether fopen() returns NULL.
  • Close every file using fclose().
  • Use the correct file mode for the intended operation.
  • Check the return values of fread(), fwrite(), fscanf(), and other file functions.
  • Use binary mode ("rb"/"wb") for binary data such as structures.
  • Use text mode for human-readable data.
  • Handle file-related errors gracefully using perror() or appropriate error messages.
  • Avoid hardcoding file paths when possible.

When NOT to Use This

Avoid file I/O when:

  • Data only needs to exist while the program is running.
  • High-speed temporary storage is better handled in memory.
  • The application requires a full-featured database instead of plain files.
  • Frequent disk access would significantly reduce performance and in-memory processing is sufficient.

Summary / Key Takeaways

  • File I/O in C programming allows programs to read and write data stored in files.
  • Files are managed using the FILE data type and functions from <stdio.h>.
  • Use fopen() to open files and fclose() to close them.
  • fprintf(), fscanf(), fgets(), fputs(), fgetc(), and fputc() are commonly used for text files.
  • fread() and fwrite() are used for binary files.
  • Always check whether file operations succeed.
  • Proper file handling helps build reliable and persistent applications.

FAQ About File I/O in C

1. What is File I/O in C?

File I/O is the process of reading data from files and writing data to files, allowing information to be stored permanently.

2. What is the purpose of fopen()?

fopen() opens a file in a specified mode (such as read, write, or append) and returns a pointer to a FILE object. If the operation fails, it returns NULL.

3. What is the difference between text files and binary files?

Text FileBinary File
Stores human-readable charactersStores raw bytes
Can be opened with a text editorMay not be readable in a text editor
Uses functions like fprintf() and fscanf()Uses functions like fread() and fwrite()

4. Why should I always close a file?

Closing a file ensures that buffered data is written to disk, releases system resources, and reduces the risk of data corruption.

5. What happens if fopen() fails?

If fopen() cannot open or create the file, it returns NULL. Your program should check this return value before performing any file operations to avoid undefined behavior.

Prev: Error HandlingBack to hub