File Handling

Last Updated : Jan 2026


In C, file handling is a fundamental part of the language that allows you to create, read, and modify files on your storage drives (SSD/HDD) instead of keeping it in volatile RAM that clears when the program terminates.

To work with files in C, you need to include the stdio.h header file. It provides functions for working with files, such as fopen(), fclose(), fread(), and fwrite().

A file pointer (FILE *fp) stores the address of this stream and tracks metadata like the current buffer status, file position indicator, and error flags.

FILE *fp = NULL; // Always initialize file pointers to NULL

fopen() & fclose()

The fopen() function is used to open a file, with specified modes.

Syntax:

file_pointer = fopen(file_name, mode);

Mode are something that tells the compiler what you want to do with the file.There are following modes:

  • r : Read mode,Read Data from the file,If the file does not exist, an error is thrown.
  • w : Write mode,Write Data to the file and previous data is cleared,If the file does not exist, it is created.
  • a : Append mode,Write Data to the end of file,If the file does not exist, it is created.
  • r+ : Read and write mode,If the file does not exist, an error is thrown.
  • w+ : Read and write mode,If the file does not exist, it is created.
  • a+ : Read and write mode,If the file does not exist, it is created.
  • rb : Read binary mode,Read Data from the file,If the file does not exist, an error is thrown.
  • wb : Write binary mode,Write Data to the file and previous data is cleared,If the file does not exist, it is created.

Example:

#include <stdio.h>

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

    // Always check if file opening succeeded!
    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Perform file operations here...

    fclose(fp); // Close stream
    return 0;
}

Reading File Data

  • fgetc(fp) : Read a single character from the file and store it in a variable.Reads the next single character from the file stream. Returns EOF (End Of File) when the end of the file is reached or an error occurs.
int ch;
while ((ch = fgetc(fp)) != EOF) {
    putchar(ch);
}
  • fgets(buffer, size, fp) : Read String Line-by-Line.Reads up to size - 1 characters or until a newline (\n) or EOF is reached. Safe against buffer overflows.
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
    printf("%s", buffer);
}
  • fread(buffer, size, count, fp) : Read data from the file into a buffer.Reads count * size bytes from the file stream and stores them in the buffer.
char buffer[100];
fread(buffer, sizeof(char), 100, fp);

Writing File Data

  • fputc(character, fp) : Write a single character to the file.Write a single character to the file stream.
fputc('S', fp);
  • fputs(string, fp) : Write a string to the file.Write a null-terminated string to the file stream.
fputs("Hello, World!\n", fp);
  • fwrite(buffer, size, count, fp) : Write data from a buffer to the file.Write count * size bytes from the buffer to the file stream.
char buffer[100];
fwrite(buffer, sizeof(char), 100, fp);

File Positioning & Utility Functions

  • fseek(fp, offset, origin) : Move the file position indicator to a specific location in the file.Move the file position indicator to a specific location in the file stream.Origin can be
    • SEEK_SET : Set the file position indicator to the beginning of the file.
    • SEEK_CUR : Set the file position indicator to the current position in the file.
    • SEEK_END : Set the file position indicator to the end of the file.
fseek(fp, 0, SEEK_SET);   // Move to start of file
fseek(fp, 10, SEEK_CUR);  // Move forward 10 bytes from current position
fseek(fp, -5, SEEK_END);  // Move 5 bytes back from the end of file
  • ftell(fp) : Get the current position of the file position indicator.Returns the current position of the file position indicator in the file stream.
long position = ftell(fp);
printf("Current byte position: %ld\n", position);
  • rewind(fp) : Move the file position indicator to the beginning of the file.Move the file position indicator to the beginning of the file stream.
rewind(fp);
  • ferror(fp) : Check if an error has occurred in the file stream.Checks if an error has occurred in the file stream.
if (ferror(fp)) {
    // Handle error...
}
  • feof(fp) : Check if the end of the file has been reached.Checks if the end of the file has been reached.
if (feof(fp)) {
    // End of file reached...
}

Note : feof() only returns true after an attempted read operation reads past the last byte of the file. Do not use while(!feof(fp)) to control read loops—check the return value of fgets or fgetc instead!


Binary Files

Appending b to any mode string (e.g., "rb", "wb", "rb+") opens the file in binary mode. Binary mode prevents platform-specific transformations of raw byte data (such as newline \n to \r\n conversions on Windows).

#include <stdio.h>

typedef struct {
    int id;
    char name[20];
    float gpa;
} Student;

int main(void) {
    Student s1 = {101, "John Doe", 3.85f};
    Student s_out;

    // 1. Write binary data
    FILE *fp = fopen("students.bin", "wb");
    if (fp == NULL) return 1;
    fwrite(&s1, sizeof(Student), 1, fp);
    fclose(fp);

    // 2. Read binary data back
    fp = fopen("students.bin", "rb");
    if (fp == NULL) return 1;
    fread(&s_out, sizeof(Student), 1, fp);
    fclose(fp);

    printf("Read Student: ID=%d, Name=%s, GPA=%.2f\n", s_out.id, s_out.name, s_out.gpa);
    return 0;
}

Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR