Mark As Completed Discussion

File Handling

In C++, file handling refers to the process of working with files, specifically reading data from files and writing data to files. This is a crucial skill to have when building real-world applications that need to interact with external files.

Reading Data from Files

To read data from a file, we need to follow a series of steps:

  1. Open the file using an input stream.
  2. Read the contents of the file.
  3. Close the file.

Here's an example of how to read data from a file:

TEXT/X-C++SRC
1#include <iostream>
2#include <fstream>
3
4int main() {
5  std::ifstream inputFile;
6  inputFile.open("data.txt");
7
8  if (!inputFile) {
9    std::cout << "Failed to open the file." << std::endl;
10    return 1;
11  }
12
13  std::string line;
14  while (std::getline(inputFile, line)) {
15    std::cout << line << std::endl;
16  }
17
18  inputFile.close();
19
20  return 0;
21}

Writing Data to Files

To write data to a file, we need to follow a similar set of steps:

  1. Open the file using an output stream.
  2. Write the data to the file.
  3. Close the file.

Here's an example of how to write data to a file:

TEXT/X-C++SRC
1#include <iostream>
2#include <fstream>
3
4int main() {
5  std::ofstream outputFile;
6  outputFile.open("output.txt");
7
8  if (!outputFile) {
9    std::cout << "Failed to open the file." << std::endl;
10    return 1;
11  }
12
13  outputFile << "Hello, world!" << std::endl;
14
15  outputFile.close();
16
17  return 0;
18}

File handling allows us to work with various types of files, such as text files, binary files, and CSV files. It's an essential skill when building applications that deal with data persistence and external file interactions.

Now that you understand the basics of file handling in C++, let's move on to more advanced concepts and techniques.

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