×
>
<

Aptitude

C++ File Handling

File Handling

In C++, file handling is a mechanism to store the output of a program in a file and to perform various operations on it such as reading, writing, appending, etc.
Definition: File handling is the process of creating, reading, updating, and deleting files using C++ functions and classes.
File handling helps in storing data permanently and efficiently.

File Handling Operations

1. Creating and Opening Files

  • Using ofstream or fstream class, you can create and open a file for writing.
  • Example: ofstream file("example.txt");

2. Reading from Files

  • Using ifstream or fstream class, you can open a file for reading.
  • Example: ifstream file("example.txt");

3. Writing to Files

  • Using ofstream or fstream class, you can write data to a file.
  • Example: file << "Hello, World!";

4. Closing Files

  • After performing operations, it is important to close the file using close() function.
  • Example: file.close();

5. Appending to Files

  • To append data to a file, open it in ios::app mode using fstream class.
  • Example: fstream file("example.txt", ios::app);

File Handling Components

To write programs for file handling in C++ effectively, you should understand the following components:

1. Include Header Files

  • To perform file operations, you need to include the fstream library which contains ifstream, ofstream, and fstream classes.

Example:

  
#include <fstream>
  
2. Creating and Opening Files

  • Create and open files using ofstream (for writing), ifstream (for reading), or fstream (for both reading and writing).

Example:

  
ofstream myfile("example.txt"); // Create and open a text file
  
3. Writing to Files

  • Write data to files using the ofstream or fstream object.

Example:

  
myfile << "Hello, World!"; // Write to the file
  
4. Reading from Files

  • Read data from files using the ifstream or fstream object.

Example:

  
ifstream myfile("example.txt"); // Open a file for reading
string line;
while (getline(myfile, line)) {
    cout << line << endl; // Output the text from the file
}
  
5. Closing Files

  • Always close the file after performing operations using the close() method.

Example:

  
myfile.close(); // Close the file
  
6. File Modes

  • File modes define how a file should be opened (e.g., ios::in for reading, ios::out for writing, ios::app for appending).

Example:

  
fstream myfile;
myfile.open("example.txt", ios::out | ios::app); // Open file for writing and appending
  
7. Checking File Status

  • Before performing operations, check if a file is open and in a good state using the is_open() and good() methods.

Example:

  
if (myfile.is_open() && myfile.good()) {
    // Perform file operations
}
  
8. Error Handling

  • Handle file errors using the fail(), bad(), and eof() methods to check for specific issues.

Example:

  
if (myfile.fail()) {
    cerr << "Error opening file" << endl;
}
  
File Handling in C++
File Handling Example: Writing and Reading a File
  
#include <iostream>
#include <fstream>
using namespace std;

void writeToFile();  // Function prototype for writing to a file
void readFromFile(); // Function prototype for reading from a file

int main() {
    writeToFile();   // Function call to write to a file
    readFromFile();  // Function call to read from a file
    return 0;
}

// Function to write data to a file
void writeToFile() {
    ofstream outFile("example.txt"); // Create and open a text file for writing
    if (outFile.is_open()) {
        outFile << "Hello, World!\n"; // Write to the file
        outFile << "Welcome to file handling in C++.\n";
        outFile.close();              // Close the file
    } else {
        cout << "Unable to open file for writing." << endl;
    }
}

// Function to read data from a file
void readFromFile() {
    ifstream inFile("example.txt");   // Open a text file for reading
    string line;
    if (inFile.is_open()) {
        while (getline(inFile, line)) { // Read the file line by line
            cout << line << endl;      // Output the text from the file
        }
        inFile.close();                // Close the file
    } else {
        cout << "Unable to open file for reading." << endl;
    }
}
  
output
  
Hello, World!
Welcome to file handling in C++.
  

  • In the above program, writeToFile() is called from main() to write data to a file named example.txt.
  • The writeToFile() function creates and opens the file, writes two lines of text, and then closes the file.
  • After that, readFromFile() is called from main() to read the contents of the file.
  • The readFromFile() function opens the file, reads its contents line by line, and prints each line to the console, then closes the file.