Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Redirect cin and cout to Files in C++?
Next article icon

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

Last Updated : 08 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

C++
// C++ program to demonstrate how to open and close a file #include <fstream> #include <iostream>  using namespace std;  int main() {     //  create and ofstream object and open the file in     //  append mode     ofstream fio("abc.txt", ios::app);      // Check if the file is opened successfully     if (fio.is_open()) {          cout << "File opened successfully." << endl;          // Append content to the file         fio << "This text is appended to the file." << endl;          // Close the file         fio.close();          cout << "File closed." << endl;     }     else {         // Display error if file was not opened         cout << "Error opening file!" << endl;     }      return 0; } 

Output
File opened successfully.  File closed.  

Next Article
How to Redirect cin and cout to Files in C++?
author
gaurav472
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-file-handling
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • How to Delete a File in C++?
    C++ file handling allows us to manipulate external files from our C++ program. We can create, remove, and update files using file handling. In this article, we will learn how to remove a file in C++. Delete a File in C++ To remove a file in C++, we can use the remove() function defined inside the
    2 min read
  • How to Hide and Show a Console Window in C++?
    The task is to hide and Show the console window of a C++ program. The program for the same is given below. Note: The results of the following program can only be seen when it is executed on a console. Example: C/C++ Code // C++ program to hide and show a console window #include <iostream> #inc
    2 min read
  • How to Redirect cin and cout to Files in C++?
    In C++, we often ask for user input and read that input using the cin command and for displaying output on the screen we use the cout command. But we can also redirect the input and output of the cin and cout to the file stream of our choice. In this article, we will look at how to redirect the cin
    2 min read
  • How to Compile C++ Code in macOS ?
    Compiling a C++ code means translating the program from the human-readable form (high-level language) to something a machine can “understand” (machine language) so that the program can run on a machine. In this article, we will learn how to compile C++ code in macOS. C++ Program Compilation in macOS
    2 min read
  • How to Read From a File in C++?
    Reading from a file means retrieving the data stored inside a file. C++ file handling allows us to read different files from our C programs. This data can be taken as input and stored in the program for processing. Generally, files can be classified in two types: Text File: Files that contains data
    4 min read
  • How to Delete a Pointer in C++?
    In C++, memory management is essential to avoid memory leaks, crashes, and undefinable behavior. In this article, we will learn how to properly delete a pointer in C++. Deleting a Pointer in C++By deleting a pointer, we refer to deleting the memory allocated to the pointer. To delete a pointer in C+
    2 min read
  • How to Check a File or Directory Exists in C++?
    Checking the presence of a directory or a file is one of the most common operations performed by a file system in an Operating System. Most programming languages offer some level of file system accessibility in form of library functions. In this article, you will learn how to test a file or director
    4 min read
  • How to Read a File Line by Line in C++?
    In C++, we can read the data of the file for different purposes such as processing text-based data, configuration files, or log files. In this article, we'll learn how to read a file line by line in C++. Read a File Line by Line in C++We can use the std::getline() function to read the input line by
    2 min read
  • How to Read File into String in C++?
    In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++. Reading Whole File into a C++ StringTo read an entire file line by line and save it into std::string, we can use std::ifstream class to
    2 min read
  • How to Read a File Character by Character in C++?
    In C++, file handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk). In this article, we will learn how to read a file character by character in C++. Example: Input: "Geeks for Geeks"Output: G e e k s f o r G e e k sRead Te
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences