File Handling in C Language

Introduction

File handling in C allows us to create, read, update and delete files. The stdio.h library provides functions for file operations.

1. File Operations

fopen() and fclose()

The basic file operations are opening and closing files:

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

int fclose(FILE *stream);

2. File Modes

Mode

Description

r

Open for reading (file must exist)

w

Open for writing (creates new or truncates existing)

a

Open for appending (creates if doesn't exist)

r+

Open for reading and writing

w+

Open for reading and writing (truncates)

a+

Open for reading and appending

3. File Functions

Function

Description

fprintf()

Writes formatted output to a file

fscanf()

Reads formatted input from a file

fgets()

Reads a string from a file

fputs()

Writes a string to a file

fgetc()

Reads a character from a file

fputc()

Writes a character to a file

4. Binary vs Text Files

Text files store data as ASCII characters while binary files store data in the same format as in memory.

Example of binary file opening:

FILE *fp = fopen("data.bin", "wb"); // write binary mode

5. Error Handling

Always check if file operations succeed:

FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
        printf("Error opening file!");
        exit(1);
}

6. File Positioning

Functions to control file pointer position:

·         fseek() - Moves file pointer to specified location

·         ftell() - Returns current position of file pointer

·         rewind() - Sets file pointer to beginning of file

7. Sample Programs

Program 1: Create and Write to File

#include <stdio.h>
int main() {
        FILE *fp = fopen("example.txt", "w");
        if (fp == NULL) {
            printf("Error creating file!");
            return 1;
        }
        fprintf(fp, "Hello File Handling in C!");
        fclose(fp);
        return 0;
}

Program 2: Read from File

#include <stdio.h>
int main() {
        FILE *fp = fopen("example.txt", "r");
        if (fp == NULL) {
            printf("Error opening file!");
            return 1;
        }
        char buffer[100];
        while (fgets(buffer, 100, fp) != NULL) {
            printf("%s", buffer);
        }
        fclose(fp);
        return 0;
}

Program 3: Student Record System

#include <stdio.h>
struct Student {
        int roll;
        char name[50];
        float marks;
};

int main() {
        struct Student s;
        FILE *fp = fopen("students.dat", "ab+");

        // Write record
        printf("Enter roll, name, marks: ");
        scanf("%d %s %f", &s.roll, s.name, &s.marks);
        fwrite(&s, sizeof(s), 1, fp);

        // Read records
        rewind(fp);
        while (fread(&s, sizeof(s), 1, fp) == 1) {
            printf("Roll: %d, Name: %s, Marks: %.2f\n",
                   s.roll, s.name, s.marks);
        }

        fclose(fp);
        return 0;
}