Basic File Handling in C

File handling in C allows you to store data permanently on storage devices. It uses the FILE pointer and related functions to create, read, write, and close files.

Introduction

C provides file handling so programs can work with real data stored in files. The header file <stdio.h> contains all file-handling functions.

Steps in File Handling

Common File Functions

File Opening Modes

Note: Always check if fopen() returns NULL to avoid crashes.

10 File Handling Examples

#include <stdio.h>

/* 1. Create & Write to a file */
int main(){
    FILE *fp = fopen("data.txt", "w");
    fprintf(fp, "Hello File!");
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 2. Read a file */
int main(){
    FILE *fp = fopen("data.txt", "r");
    char text[50];
    fgets(text, 50, fp);
    printf("%s", text);
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 3. Append data to a file */
int main(){
    FILE *fp = fopen("data.txt", "a");
    fputs("New Line Added\n", fp);
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 4. Write integers using fprintf */
int main(){
    FILE *fp = fopen("numbers.txt", "w");
    int a=10, b=20;
    fprintf(fp, "A=%d B=%d", a, b);
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 5. Read integers using fscanf */
int main(){
    FILE *fp = fopen("numbers.txt", "r");
    int a, b;
    fscanf(fp, "A=%d B=%d", &a, &b);
    printf("%d %d", a, b);
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 6. Write character-by-character */
int main(){
    FILE *fp = fopen("char.txt", "w");
    fputc('A', fp);
    fputc('B', fp);
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 7. Read character-by-character */
int main(){
    FILE *fp = fopen("char.txt", "r");
    char c;
    while((c = fgetc(fp)) != EOF){
        printf("%c ", c);
    }
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 8. Read multiple lines */
int main(){
    FILE *fp = fopen("text.txt", "r");
    char line[100];
    while(fgets(line, sizeof(line), fp)){
        printf("%s", line);
    }
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 9. Count characters in a file */
int main(){
    FILE *fp = fopen("data.txt", "r");
    int count=0;
    while(fgetc(fp)!=EOF) count++;
    printf("Total characters: %d", count);
    fclose(fp);
    return 0;
}
#include <stdio.h>

/* 10. Check if file exists */
int main(){
    FILE *fp = fopen("hello.txt", "r");
    if(fp == NULL)
        printf("File not found!");
    else {
        printf("File exists.");
        fclose(fp);
    }
    return 0;
}

Practice Questions

  1. What is a file? Why is file handling needed?
  2. List common file modes in C.
  3. Difference between text and binary files?
  4. Write a program to count words in a file.
  5. Write a program to copy one file to another.
Create a file "student.txt" and store name, age, and marks of a student using fprintf(). Then read and display the data.