Introduction

File operations in C provide mechanisms to read, write, and manipulate data stored in files. In traditional desktop systems, this involves working with the operating system’s file system. However, in embedded systems, file operations are relevant when using external storage like SD cards, EEPROMs, or flash memory, often with the help of libraries like FatFs or LittleFS.

To open and modify a file, we utilize a special FILE type pointer. This file pointer is an integer which stores the descriptor of the file that is opened. All the operations on the file are performed using this file pointer and is crucial throughout the lifetime of the file.

File I/O in Traditional C

Functions for File Handling

The stdio.h library provides core functions for file handling:

FunctionDescription
fopen()Opens a file
fclose()Closes a file
fread()Reads data from a file
fwrite()Writes data to a file
fprintf()Writes formatted data
fscanf()Reads formatted data
fseek()Moves file pointer
ftell()Returns file pointer position
fflush(fp)Flushes data from buffer to file
f_rename()Renames a file
f_unlink()Deletes a file
opendir()Opens a folder/directory
readdir()Reads the contents of the folder

File Opening Modes

There are many file operating modes. Each mode modifies the file in different manner and restrict from certain actions for the period of execution.

ModeDescription
"r"Read only
"w"Write only (creates or truncates)
"a"Append to file
"r+"Read & write
"w+"Write & read (truncates file)
"a+"Read & append

Example

#include <stdio.h>
 
int main() {
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }
 
    fprintf(fp, "Temperature = %d°C\n", 25);
    fclose(fp);
    return 0;
 
}

File Operations in Embedded C

Embedded systems may not have a traditional file system. File operations are used when:

  • An SD card or USB mass storage is connected

  • A file system like FatFs is used

  • EEPROM or flash memory is abstracted as a file system

Libraries for File Systems in Embedded C

  • FatFs – for SD card FAT file systems

  • LittleFS – for NOR/NAND flash

  • SPIFFS – small embedded file system

C File I/O vs Embedded FS

Featurestdio.h (PC)FatFs (Embedded)
File openingfopen()f_open()
File writingfprintf()f_write()
Directory handling<dirent.h>f_opendir(), f_readdir()
File system mountNot neededf_mount()