File Handling in C/C++: Read, Write, Append Operations

0
73
File Handling in C/C++

In every real-world software application, storing data beyond the runtime of a program is essential. That’s where File Handling in C/C++ becomes a core skill. Whether you are developing a log system, a student database, or an automation script, managing data with files is critical.

In this guide by Kamlesh Singad from Code With Kamlesh, we’ll break down file operations into digestible pieces using examples, making it effortless for beginners to grasp Strings & File Handling concepts in C/C++.

Why Learn File Handling in Programming?

Imagine a calculator that forgets every input you ever gave it. Not very helpful, right?

File handling allows:

  • Persistent data storage
  • Log maintenance
  • Inter-program communication
  • Data transfer across platforms

Whether you’re in development or competitive coding, file handling builds a bridge between theory and practical utility.

Also Read: Pointers in C/C++: Basics and Advanced Concepts – Complete Guide

File Handling in C/C++

Basics of Files in C and C++

Files in C/C++ come in two forms:

  • Text Files: Store human-readable content (.txt, .csv)
  • Binary Files: Store machine-readable data (.dat, .bin)

To use files, you must perform three core actions:

  1. Open a file
  2. Perform read/write/append
  3. Close the file

Let’s start with the C-style file handling.

File Handling in C: Read, Write, Append Operations

Opening and Closing Files in C

Use the fopen() function to open a file:

FILE *fptr = fopen("example.txt", "w");

To close:

fclose(fptr);
File Handling in C/C++

File Modes in C

ModeDescription
"r"Read only
"w"Write only (creates new)
"a"Append only
"r+"Read and Write
"w+"Write and Read (truncates)
"a+"Append and Read

Reading from a File in C

FILE *fptr = fopen("data.txt", "r");
char buffer[100];
fgets(buffer, 100, fptr);
printf("Content: %s", buffer);
fclose(fptr);

Writing to a File in C

FILE *fptr = fopen("output.txt", "w");
fprintf(fptr, "Welcome to Code With Kamlesh!");
fclose(fptr);

Appending Data to a File in C

FILE *fptr = fopen("log.txt", "a");
fputs("New log entry\n", fptr);
fclose(fptr);

Also Read: Arrays in C/C++: Single & Multi-dimensional

File Handling in C++: Stream-Based Approach

C++ enhances file handling using classes from the <fstream> library:

  • ifstream for reading
  • ofstream for writing
  • fstream for both
#include <fstream>
using namespace std;

ofstream file("example.txt");
file << "Hello, C++ File Handling!";
file.close();
File Handling in C/C++

Reading from a File in C++

ifstream file("example.txt");
string line;
while(getline(file, line)) {
    cout << line << endl;
}
file.close();

Appending Data to a File in C++

ofstream file("example.txt", ios::app);
file << "Appended line\n";
file.close();

Handling Errors in File Operations

Always check if a file was opened successfully:

FILE *fptr = fopen("data.txt", "r");
if (fptr == NULL) {
    perror("Error opening file");
}
ifstream file("missing.txt");
if (!file) {
    cerr << "Unable to open file";
}

Practical Example: Student Record Management

Let’s build a simple student record system using structs and files in C:

struct Student {
    char name[50];
    int age;
};

void writeStudent() {
    FILE *fptr = fopen("students.txt", "a");
    struct Student s = {"Ravi", 20};
    fwrite(&s, sizeof(struct Student), 1, fptr);
    fclose(fptr);
}

Also Read: Understanding Scope, Lifetime, and Storage Classes in C/C++

Best Practices for File Handling

  • Always close files with fclose() or .close()
  • Check for file open errors
  • Use buffer flushing when needed
  • Handle both text and binary formats when required
  • Avoid hardcoding paths

FAQs

What are the basic file operations in C and C++?
Read, write, and append operations are the core file operations.

Which is better: fopen() or fstream?
fopen() is standard in C, while fstream is safer and more flexible in C++.

How do you check if a file exists before opening it in C++?
Use ifstream file("filename"); if(file) to check.

What happens if you forget to close a file?
It may lead to data loss, memory leaks, or file locks.

Can we write structures to a file?
Yes, especially in binary mode using fwrite() in C.

Is file handling part of string operations?
Yes, strings are commonly used to read from and write to files.

Conclusion

File Handling in C/C++ is a vital skill that bridges logic and practicality in programming. From reading configurations to logging events, file operations empower your code with memory beyond runtime. Guided by Kamlesh Singad from Code With Kamlesh, you’re now equipped with the theoretical clarity and hands-on techniques to master Strings & File Handling.

LEAVE A REPLY

Please enter your comment!
Please enter your name here