VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-open-and-close-file-in-cpp/

⇱ How to Open and Close a File in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Open and Close a File in C++?

Last Updated : 23 Jul, 2025

In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++.

Open and Close a File in C++

The fstream class contains the std::fstream::open() function that can be used to open files in different modes.

Syntax of fstream::open()

fstream_object.open(filename, mode);

The modes can be of three types:

  • std::ios::in: This mode is used to open a file for reading only.
  • std::ios::out: This mode is used to open a file for writing. If there is already content in the file then it will be overwritten in this mode.
  • std::ios::app: This mode is called the append mode in which we open a file for writing at the end of the file.

We can close the file using std::fstream::close() function.

Algorithm

1. We will first create an fstream object.
2. Then we open the file using open() function in write mode(ios::out)
2. We then write some data to the file.
3. At the end, we close the file using close() function

C++ Program to Open and Close a File


Output
File opened successfully.
File closed.
Comment