File Streams

File streams in C++ provide a powerful mechanism for handling input and output operations with external files. They allow us to read data from files and write data to files seamlessly, making file manipulation an integral part of programming.

The Basics of File Streams

In C++, file streams are managed through classes provided by the Standard Template Library (STL). The primary classes for file streams are:

  • ifstream: Used for reading input from a file.
  • ofstream: Used for writing output to a file.
  • fstream: Provides functionality for both input and output operations.

Opening and Closing Files

Before performing any operations on a file, we need to open it using the appropriate file stream class. After we’re done with the operations, it’s essential to close the file to release system resources.

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

int main() {
    // Open a file for writing
    ofstream outputFile("output.txt");

    if (!outputFile) {
        cout << "Error: Unable to open file";
        return 1;
    }

    // Write data to the file
    outputFile << "Hello, World!\n";
    outputFile << "This is a new line.";

    // Close the file
    outputFile.close();

    return 0;
}

				
			

Reading from Files

To read data from a file, we use the ifstream class. We can read data line by line or character by character using various methods provided by the ifstream class.

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

int main() {
    // Open a file for reading
    ifstream inputFile("input.txt");

    if (!inputFile) {
        cout << "Error: Unable to open file";
        return 1;
    }

    // Read data from the file
    string line;
    while (getline(inputFile, line)) {
        cout << line << endl;
    }

    // Close the file
    inputFile.close();

    return 0;
}

				
			

Binary File Handling

In addition to text files, C++ supports handling binary files, allowing us to work with non-textual data efficiently.

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

int main() {
    // Define a struct for demonstration
    struct Record {
        int id;
        char name[20];
        double salary;
    };

    // Open a binary file for writing
    ofstream outputFile("data.bin", ios::binary);

    if (!outputFile) {
        cout << "Error: Unable to open file";
        return 1;
    }

    // Create a record
    Record employee = {1, "John Doe", 5000.00};

    // Write the record to the binary file
    outputFile.write(reinterpret_cast<char*>(&employee), sizeof(Record));

    // Close the file
    outputFile.close();

    return 0;
}

				
			

Advanced File Stream Techniques

File Modes and Flags File streams in C++ support different modes and flags that allow us to control various aspects of file handling. Some common modes and flags include:

  • ios::in: Open file for reading.
  • ios::out: Open file for writing.
  • ios::app: Append mode, writing operations append data at the end of the file.
  • ios::binary: Open file in binary mode, useful for non-text files.
				
					#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Open a file in binary mode for writing
    ofstream outputFile("data.bin", ios::out | ios::binary);

    if (!outputFile) {
        cout << "Error: Unable to open file";
        return 1;
    }

    // Write data to the file
    int data[] = {10, 20, 30, 40, 50};
    outputFile.write(reinterpret_cast<char*>(data), sizeof(data));

    // Close the file
    outputFile.close();

    // Open the file in append mode for reading
    ifstream inputFile("data.bin", ios::in | ios::app | ios::binary);

    if (!inputFile) {
        cout << "Error: Unable to open file";
        return 1;
    }

    // Read data from the file
    int readData[5];
    inputFile.read(reinterpret_cast<char*>(readData), sizeof(readData));

    // Output the read data
    cout << "Data read from file: ";
    for (int i = 0; i < 5; ++i) {
        cout << readData[i] << " ";
    }
    cout << endl;

    // Close the file
    inputFile.close();

    return 0;
}

				
			
				
					// output //
Data read from file: 10 20 30 40 50

				
			

Explanation:

  • The program first opens a file named “data.bin” in binary mode for writing (ios::out | ios::binary). If the file cannot be opened, it prints an error message and exits.
  • An array of integers data is defined and written to the file using the write() function.
  • The file is then closed.
  • Next, the program opens the same file in append mode for reading (ios::in | ios::app | ios::binary), allowing both reading and appending to the file.
  • Data is read from the file into an array readData using the read() function.
  • Finally, the program outputs the data read from the file and closes the file.

File streams in C++ provide a versatile and efficient way to handle input and output operations with external files. By understanding the basics of file streams, including opening and closing files, reading from and writing to files, and employing advanced techniques like file modes, error handling, and binary file handling, programmers can effectively manage file manipulation tasks in their C++ programs.Happy coding !❤️

Table of Contents