File and Streams in C++

File handling in C++ involves reading from and writing to files. You can achieve this using file streams, which are classes in the C++ Standard Library designed to work with files.
There are two main types of file streams: ifstream for input (reading) and ofstream for output (writing). If you want to perform both reading and writing, you can use the fstream class.

Necessary headers File

#include<iostream>
#include<fstream>

Writing to a File

int main() {
    // Step 1: Create an output file stream
    std::ofstream outFile("output.txt");
    // Step 2: Check if the file was opened successfully
    if (!outFile) {
        std::cerr << "Failed to open output file." << std::endl;
        return 1;
    }
    // Step 3: Write data to the file using the << operator
    outFile << "Hello, File Handling in C++!" << std::endl;
    // Step 4: Close the file stream
    outFile.close();
    return 0;
}

In the above example, we use the ofstream class from the <fstream> header. We create an instance of ofstream named outputFile and open the file "output.txt". We then use the << operator to write data to the file, just like using cout for standard output. Finally, we close the file using the .close() method.

Reading from a File

int main() {
    // Step 1: Create an input file stream
    std::ifstream inFile("input.txt"); 
    // Step 2: Check if the file was opened successfully
    if (!inFile) {
        std::cerr << "Failed to open input file." << std::endl;
        return 1;
    }
    // Step 3: Read data from the file using a loop and std::getline()
    std::string line;
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl; // Print each line read from the file
    }
    // Step 4: Close the file stream
    inFile.close();
    return 0;
}

In the above example, we use the ifstream class from the <fstream> header. We create an instance of ifstream named inputFile and open the file "input.txt". We then use the std::getline() function to read lines from the file and print them to the standard output.