Opening and Closing a File in C++


What is a File?

The file is a collection of data that can be in any format, and it may be text, image, or video. When you open the file in the program, it gets converted into a byte stream which gets used for communication.

File handling in C++

We need to handle data; we need to use some repeatedly, so the file is an excellent option to handle repeat data. In C++, there are various header files or libraries for file handling, allowing users to create, edit, open, delete or update any file. C++ uses different classes to perform this operation on the file. The classes used by C++ are as follows

  • ofstream : This class is used to write in the file.
  • ifstream: This class is used to read data from file
  • fstream: This class is used to read and write in the file.

Opening a file

To open any file, we always need a path from which we can access it. In C++, the ifstream class constructor gets used to open the file.

Syntax :

  • ifstream(const char* filename, ios_base::openmode mode= ios_base::in);
  • ifstream fin(filename, openmode); // by default the mode is ios_base::in
  • ifstream fin(“filename”);

Open file using open method

  • ifstream fin;
  • fin.open(filename, openmode);
  • din.open(“filename”);

Example Open file using open method:

#include <fstream> #include <iostream> using namespace std; int main() { string str1; // Open a file in read mode in your pc ifstream infile; infile.open("test.txt"); cout << "Fatching from the test.txt\n"; //Fatching data at the screen while (infile) { getline(infile, str1); cout << str1; } // Close the opened file infile.close(); return 0; }

OUTPUT:

file type

Closing a file

The ofstream, ifstream, and fstream classes have a close() method to close the current object or to close the current object.

Syntax :

Void close();