Part 4 — Chapter 18

Chapter 18: File Handling

So far, program data existed only while the program was running. Once the program ended, all variable data stored in memory was lost. File handling allows programs to store and retrieve data permanently using files stored on disk.

C provides file handling functions through the <stdio.h> library.

What is a File?

A file is a collection of data stored permanently on a storage device such as a hard disk, SSD, or flash memory.

Files allow programs to:

  • Save data permanently
  • Read previously stored information
  • Process large amounts of data
  • Exchange data between programs

File Pointer

In C, files are accessed using a special pointer called a file pointer.

Syntax

syntax
C
FILE *fp;

The FILE type is defined inside <stdio.h>.

Opening a File

The fopen() function is used to open a file.

Syntax

syntax
C
fp = fopen("filename", "mode");

Common File Modes

Mode Purpose
"r" Open file for reading
"w" Open file for writing
"a" Open file for appending
"r+" Read and write
"w+" Read and write (overwrites file)
Example Program & Output [ Click to View ]
file_write.c
C
#include <stdio.h>

int main()
{
    FILE *fp;

    fp = fopen("data.txt", "w"); // opens in write mode

    if(fp == NULL)
    {
        printf("File opening failed");
        return 1;
    }

    fprintf(fp, "Hello File"); // writes data

    fclose(fp); // closes file

    printf("Data written successfully");

    return 0;
}

Output

Data written successfully

Note: "w" mode autocreates missing files.

Reading from a File

The fscanf() function reads formatted data from a file.

Example

syntax
C
fscanf(fp, "%s", data);
Closing a File

The fclose() function closes an opened file.

Syntax

syntax
C
fclose(fp);

Closing files properly prevents resource leaks and ensures data is saved correctly.

File Handling Flow

Open File
Read / Write Data
Close File

Important Points

  • Files store data permanently outside normal program memory
  • FILE * pointers are used to access and manage files
  • Always check if fopen() returns NULL before performing file operations
  • fclose() should be used to properly save data and release file resources

Embedded Focus

File handling is used in embedded Linux systems, logging systems, configuration storage, and SD card interfaces.

system_log.c
C
FILE *log = fopen("sensor_log.txt", "a");

Embedded applications often use files for storing logs, configuration parameters, sensor readings, and communication data.

← Chapter 17: Dynamic Memory Chapter 19: Header Files →