File handling

To perform file handling in C++, you can follow these steps:

  1. Include the necessary header file: Begin by including the <fstream> header file, which provides the necessary functionalities for file handling in C++.

  2. Declare file stream objects: Declare objects of the ifstream class to read from a file, or objects of the ofstream class to write to a file. Alternatively, you can use the fstream class, which can be used for both reading and writing.

  3. Open a file: Use the open() function of the file stream object to open a file. You need to provide the filename as a parameter to this function. You can specify the file mode as well, such as ios::in for input, ios::out for output, or ios::app for appending to an existing file.

  4. Check if the file is open: After opening the file, you can check if the file is successfully opened or not using the is_open() function. It returns true if the file is open and false otherwise.

  5. Read from or write to the file: If you opened the file in input mode, you can use functions like getline(), >>, or get() to read data from the file. If you opened the file in output mode, you can use functions like write(), <<, or put() to write data to the file.

  6. Close the file: After you finish reading from or writing to the file, use the close() function of the file stream object to close the file. This step is important to release the resources associated with the file.

Here is an example of file handling in C++:

#include <fstream>
using namespace std;

int main() {
  ofstream outputFile;
  outputFile.open("example.txt");

  if (outputFile.is_open()) {
    outputFile << "This is an example text." << endl;
    outputFile.close();
  }

  ifstream inputFile;
  inputFile.open("example.txt");

  if (inputFile.is_open()) {
    string line;
    while (getline(inputFile, line)) {
      cout << line << endl;
    }
    inputFile.close();
  }

  return 0;
}

In this example, the program opens a file called "example.txt" in output mode, writes a line of text to it, and then closes it. After that, it opens the same file in input mode, reads the content line by line, and prints it to the console.

I hope this explanation helps you understand the basic steps involved in file handling in C++.