Mark As Completed Discussion

File Input and Output

File Input and Output is an essential aspect of programming that involves reading data from files and writing data to files. This capability allows your programs to store and retrieve data persistently on the computer's storage.

In C++, file input is typically done using the ifstream class, while file output is accomplished using the ofstream class. Both of these classes are defined in the <fstream> header.

To write data to a file, you can create an instance of the ofstream class, specify the file name, and open it for writing using the open() method. Then, you can write data to the file using the << operator, similar to how you output data to the console.

TEXT/X-C++SRC
1#include <fstream>
2using namespace std;
3
4int main() {
5    // Create a file
6    ofstream outputFile("output.txt");
7
8    // Write to the file
9    outputFile << "Hello, World!";
10
11    // Close the file
12    outputFile.close();
13
14    return 0;
15}

To read data from a file, you can create an instance of the ifstream class, specify the file name, and open it for reading using the open() method. Then, you can use the getline() function to read data line by line from the file.

TEXT/X-C++SRC
1#include <fstream>
2using namespace std;
3
4int main() {
5    // Open the file
6    ifstream inputFile("output.txt");
7
8    // Read from the file
9    string line;
10    while (getline(inputFile, line)) {
11        cout << line << endl;
12    }
13
14    // Close the file
15    inputFile.close();
16
17    return 0;
18}

In the example above, the program creates a file named output.txt and writes the string "Hello, World!" to it. Then, it opens the file, reads the content line by line using getline(), and outputs the lines to the console.

File Input and Output is crucial in many real-world applications, such as reading configuration files, processing large datasets, and storing program data persistently.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment