Mark As Completed Discussion

File input and output is an important concept in C++ programming. It allows you to read data from files and write data to files, which is useful for tasks such as storing and retrieving information.

To perform file input and output in C++, you need to include the <fstream> header file. This header file provides the necessary classes and functions to work with files.

Let's start with an example that demonstrates writing data to a file and then reading it back. In the code below, we first create a file stream object for writing using the ofstream class. We then open a file named "example.txt" using the open function. We write the data "Hello, World!" to the file using the output stream << operator. Finally, we close the file.

TEXT/X-C++SRC
1#include <iostream>
2#include <fstream>
3using namespace std;
4
5int main() {
6  // Create a file stream object for writing
7  ofstream outfile;
8  outfile.open("example.txt");
9
10  // Write data to the file
11  outfile << "Hello, World!";
12
13  // Close the file
14  outfile.close();
15
16  // Create a file stream object for reading
17  ifstream infile;
18  infile.open("example.txt");
19
20  // Read data from the file
21  string data;
22  infile >> data;
23
24  // Print the data
25  cout << "Data read from file: " << data << endl;
26
27  // Close the file
28  infile.close();
29
30  return 0;
31}

This code creates a file stream object outfile of type ofstream for writing. It opens the file "example.txt" using the open function, writes the data "Hello, World!" to the file using the << operator, and then closes the file.

Then, it creates a file stream object infile of type ifstream for reading. It opens the file "example.txt" using the open function, reads the data from the file using the >> operator into the variable data, and then closes the file. Finally, it prints the data read from the file, which in this case is "Hello, World!".

Output:

SNIPPET
1Data read from file: Hello, World!
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment