Computer Programming File Handling


Computer Programming – File Handling with Examples (C, C++, Java, Python, PHP)

File handling allows a program to store, read, write, update, and delete data from physical files on your computer.
It is one of the most essential features of real-world applications such as:

  • Saving user data
  • Reading configuration files
  • Writing logs
  • Processing documents
  • Managing databases

File handling operations are quite similar across programming languages, but the syntax varies.


Why File Handling Is Important?

  • Data persists even after program termination
  • Allows automation of data processing
  • Helps store large amounts of information
  • Useful for building applications like text editors, databases, and web servers

Common File Operations

Most programming languages support the following operations:

  • Create a file
  • Open a file
  • Read data from a file
  • Write data to a file
  • Append data to a file
  • Close a file
  • Delete or rename files (language-specific)

File Handling Modes (General)

ModeDescription
rRead-only mode
wWrite mode (overwrite file)
aAppend mode
r+Read & write
w+Read & write (overwrite)
a+Read & append
file handling, programming file operations, read file, write file, append file, C file handling, Java file handling, Python file handling, PHP file operations, fstream, FileWriter

File Handling in Different Programming Languages

Below are simple examples in C, C++, Java, Python, and PHP.


1. File Handling in C (stdio.h)

Write to a File

#include <stdio.h>

int main() {
    FILE *fp = fopen("test.txt", "w");
    fprintf(fp, "Hello File Handling in C!");
    fclose(fp);
    return 0;
}

Read from a File

#include <stdio.h>

int main() {
    char data[100];
    FILE *fp = fopen("test.txt", "r");
    fgets(data, 100, fp);
    printf("%s", data);
    fclose(fp);
    return 0;
}

2. File Handling in C++ (fstream)

Write

#include <fstream>
using namespace std;

int main() {
    ofstream file("data.txt");
    file << "Hello from C++!";
    file.close();
}

Read

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    string text;
    ifstream file("data.txt");
    getline(file, text);
    cout << text;
}

3. File Handling in Java

Write

import java.io.*;

public class FileWrite {
    public static void main(String[] args) throws Exception {
        FileWriter fw = new FileWriter("data.txt");
        fw.write("Hello Java File Handling!");
        fw.close();
    }
}

Read

import java.io.*;

public class FileRead {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("data.txt"));
        System.out.println(br.readLine());
        br.close();
    }
}

4. File Handling in Python

Write

f = open("data.txt", "w")
f.write("Hello from Python!")
f.close()

Read

f = open("data.txt", "r")
print(f.read())
f.close()

5. File Handling in PHP

Write

<?php
$file = fopen("data.txt", "w");
fwrite($file, "Hello from PHP!");
fclose($file);
?>

Read

<?php
$file = fopen("data.txt", "r");
echo fread($file, filesize("data.txt"));
fclose($file);
?>

Error Handling in File Operations

You must handle possible issues like:

  • File not found
  • No permission
  • Disk full
  • File locked by another program

Example (Python safe open):

try:
    with open("test.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found!")

Binary File Handling

Many languages allow reading/writing binary files:

Example (C):

fwrite(&num, sizeof(num), 1, fp);
fread(&num, sizeof(num), 1, fp);

Used for images, audio, compiled files, etc.


FAQ

1. What is file handling in programming?

File handling refers to creating, reading, writing, appending, and managing data stored in files.

2. Why is file handling important?

It allows data to be stored permanently even after the program ends.

3. What are common file modes?

r, w, a, r+, w+, a+ depending on reading, writing, and appending.

4. How do binary files differ from text files?

Binary files store data in machine-readable format, while text files store human-readable characters.

5. Which languages support file handling?

Almost all modern languages — C, C++, Java, Python, PHP, Ruby, etc.

6. What happens if I try to read a missing file?

Most languages throw an error like FileNotFound, which must be handled using exception or error checks.

Related Article
Python Cheat Sheet — Complete Syntax Reference and Programming Examples

This Python Cheat Sheet is your quick reference guide for writing efficient Python code. Whether you’re preparing for coding interviews, Read more

Computer Programming Tutorial for Beginners – Learn Coding Step by Step (C, Python, Java)

Computer Programming Tutorial for Beginners – Learn Coding Step by Step Computer programming is the process of writing a series Read more

Computer Programming Overview

Computer Programming Overview Computer programming begins with understanding what a computer program is and how it operates. A computer program Read more

Computer Programming Basics

Computer Programming – Basics Understanding computer programming begins with learning the foundational building blocks that every programming language is built Read more

Computer Programming Environment

Computer Programming – Environment Before writing your first computer program, you must prepare the correct programming environment. Although the environment Read more

Computer Programming – Basic Syntax

Before diving into advanced programming concepts, it’s important to understand how basic syntax works in different Computer Programming languages. Syntax Read more

Computer Programming – Data Types

Data types are one of the most important concepts in programming. A data type defines the kind of data a Read more

Computer Programming Variables

In any programming language, a variable is one of the most fundamental concepts. A variable acts as a named storage Read more

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments