Learn C++ practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, certification courses.
Created with over a decade of experience and thousands of feedback.
Introduction to C++
Getting Started With C++
- Your First C++ Program
- C++ Comments
C++ Fundamentals
- C++ Keywords and Identifiers
- C++ Variables, Literals and Constants
- C++ Data Types
- C++ Type Modifiers
- C++ Constants
- C++ Basic Input/Output
- C++ Operators
Flow Control
- C++ Relational and Logical Operators
- C++ if, if...else and Nested if...else
- C++ for Loop
- C++ while and do...while Loop
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ switch..case Statement
- C++ Ternary Operator
- C++ Functions
- C++ Programming Default Arguments
- C++ Function Overloading
- C++ Inline Functions
- C++ Recursion
Arrays and Strings
- C++ Array to Function
- C++ Multidimensional Arrays
- C++ String Class
Pointers and References
- C++ Pointers
- C++ Pointers and Arrays
- C++ References: Using Pointers
- C++ Call by Reference: Using pointers
- C++ Memory Management: new and delete
Structures and Enumerations
- C++ Structures
- C++ Structure and Function
- C++ Pointers to Structure
- C++ Enumeration
Object Oriented Programming
- C++ Classes and Objects
- C++ Constructors
- C++ Constructor Overloading
- C++ Destructors
- C++ Access Modifiers
- C++ Encapsulation
- C++ friend Function and friend Classes
Inheritance & Polymorphism
- C++ Inheritance
- C++ Public, Protected and Private Inheritance
- C++ Multiple, Multilevel and Hierarchical Inheritance
- C++ Function Overriding
- C++ Virtual Functions
- C++ Abstract Class and Pure Virtual Function
STL - Vector, Queue & Stack
- C++ Standard Template Library
- C++ STL Containers
- C++ std::array
- C++ Vectors
- C++ Forward List
- C++ Priority Queue
STL - Map & Set
- C++ Multimap
- C++ Multiset
- C++ Unordered Map
- C++ Unordered Set
- C++ Unordered Multiset
- C++ Unordered Multimap
STL - Iterators & Algorithms
- C++ Iterators
- C++ Algorithm
- C++ Functor
Additional Topics
- C++ Exceptions Handling
C++ File Handling
- C++ Ranged for Loop
- C++ Nested Loop
- C++ Function Template
- C++ Class Templates
- C++ Type Conversion
- C++ Type Conversion Operators
- C++ Operator Overloading
Advanced Topics
- C++ Namespaces
C++ Preprocessors and Macros
- C++ Storage Class
- C++ Bitwise Operators
C++ Buffers
- C++ istream
- C++ ostream
C++ Tutorials
- C++ freopen()
- C++ fopen()
- C++ remove()
- C++ fgetc()
File handling in C++ is a mechanism to create and perform read/write operations on a file.
We can access various file handling methods in C++ by importing the <fstream> class.
<fstream> includes two classes for file handling:
- ifstream - to read from a file.
- ofstream - to create/open and write to a file.
Note: Our online compiler cannot handle file handling right now. So, please install an IDE or text editor on your computer to run the programs given here.
Opening and Closing a File
In order to work with files, we first need to open them. In C++, we can open a file using the ofstream and ifstream classes.
For example, here's how we can open a file using ofstream :
- my_file - the name of the object of the ofstream class.
- example.txt - the name and extension of the file we want to open.
Note: We can also use the open() function to open a file. For example,
Closing a File
Once we're done working with a file, we need to close it using the close() function.
Let's take an example program to look at these operations.
- Example 1: Opening and Closing a File
This code will open and close the file example.txt .
Note : If there's no such file to open, ofstream my_file("example.txt"); will instead create a new file named example.txt .
- Check the File for Errors
In file handling, it's important to ensure the file was opened without any error before we can perform any further operations on it.There are three common ways to check files for errors:
1. By Checking the File Object
Notice the condition in the if statement:
This method checks if the file is in an error state by evaluating the file object itself.
- If the file has been opened successfully, the condition evaluates to true .
- If there's an error, it evaluates to false , and you can handle the error accordingly.
2. Using the is_open() Function
The is_open() function returns
- true - if the file was opened successfully.
- false - if the file failed to open or if it is in a state of error.
For example,
3. Using the fail() Function
The fail() function returns
- true - if the file failed to open or if it is in a state of error.
- false - if the file was opened successfully.
Note: For simplicity, we recommend using the first method.
- Read From a File
Reading from text files is done by opening the file using the ifstream class. For example,
Then, we need to read the file line-by-line. To do this, we need to loop through each line of the file until all the lines are read, i.e., until we reach the end of the file .
We use the eof() function for this purpose, which returns
- true - if the file pointer points to the end of the file
- false - if the file pointer doesn't point to the end of the file
Here, the while loop will run until the end of the file. In each iteration of the loop,
- getline(my_file, line); reads the current line of the file and stores it in the line variable.
- Then, it prints the line variable.
Next, let's clarify this with a working example.
Example 2: Read From a File
Suppose example.txt contains the following text:
Then, our terminal will print the following output:
- Write to a File
We use the ofstream class to write to a file. For example,
We can then write to the file by using the insertion operator << with the ofstream object my_file . For example,
Notice the following code for writing to the file:
This is similar to printing output to a screen:
In file handling, we just replace cout with the file object to write to the file instead of the console.
Our particular code will write the following text to example.txt :
Note: Writing to an existing file will overwrite the existing contents of the file.
- Append to a Text File
To add/append to the existing content of a file, you need to open the file in append mode.
In C++, you can achieve this by using the ios::app flag when opening the file:
Now, let's add some more text to the existing content of example.txt :
This will add the following lines to example.txt :
- File Handling With fstream
Instead of using ifstream to read from a file and ofstream to write to the file, we can simply use the fstream class for all file operations.
The constructor for fstream allows you to specify the file name and the mode for file operations.
Let's look at an example:
If we look at the file after running the program, we will find the following contents:
Note : Using ifstream and ofstream explicitly signifies the intention of reading or writing, respectively, making the code more readable and less prone to errors. Using fstream for both might lead to ambiguity or unintended operations if not handled carefully.
Table of Contents
- Introduction
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
- Interactive Courses
- Certificates
- 2000+ Challenges
Related Tutorials
C++ Tutorial
C++ std Namespace
- For educators
- English (US)
- English (India)
- English (UK)
- Greek Alphabet
This problem has been solved!
You'll get a detailed solution from a subject matter expert that helps you learn core concepts.
Question: 6.1 Question 2Goal: Learn to handle and write to files.Assignment: Given a file named work_journal.log present in the current working directory, write code that does the following:1. Open the file2. Append the following lines of text at the end of the file, making sure it's on new lines:---12-01-2023Work completed3. Close the file**MY Code** - Please
Recognizing the Problem: The use of the 'w' mode while opening the file is the main problem with your...
Not the question you’re looking for?
Post any question and get expert help quickly.
IMAGES
VIDEO