Launch your tech mastery with us—your coding journey starts now!
Course Content
Basic Syntax and Data Types
0/2
Arrays and Strings
0/2
Structures in C
0/1
Dynamic Memory Management
0/1
Command Line Arguments
0/1
Preprocessor Directives
0/1
C Programming

Definition:
File handling allows us to store program output in a file and read data from a file — useful for permanent data storage.

Types of File Operations:

  1. fopen() – Opens a file
  2. fprintf() / fscanf() – Write/Read formatted data
  3. fgetc() / fputc() – Read/Write single characters
  4. fgets() / fputs() – Read/Write strings
  5. fclose() – Closes a file

Modes in fopen():

Mode

Description

“r”

Open for reading

“w”

Open for writing (creates new or overwrites)

“a”

Append to file

“r+”

Read & write

“w+”

Write & read

“a+”

Append & read

Example – Writing to a file:

#include <stdio.h>

int main() {

    FILE *fptr;

    fptr = fopen(“data.txt”, “w”);

    if (fptr == NULL) {

        printf(“Error opening file!”);

        return 1;

    }

    fprintf(fptr, “Hello File Handling!”);

    fclose(fptr);

    return 0;

}

Example – Reading from a file:

#include <stdio.h>

int main() {

    FILE *fptr;

    char ch;

    fptr = fopen(“data.txt”, “r”);

    while ((ch = fgetc(fptr)) != EOF) {

        putchar(ch);

    }

    fclose(fptr);

    return 0;

}