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 Read Data from a CSV File to a 2D Array in C++?
Next article icon

How to Read From a File in C++?

Last Updated : 12 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Text File: Files that contains data in the form of text (characters).
  2. Binary File: Files that contains data in raw binary form.

The method of reading data from these files also differs from one another. Let's see how to read each type of files.

Read From a Text File

To read the content of this text file in C++, we have to first create an input file stream std::ifstream to the file in default flags. After that, we can use any input function, such as std::getline() or >> operator to read the textual data and store it in the string variable. We generally prefer getline() as it reads till the newline, or any specified character is found.

Example

Assume that your text file has name textFile.txt and contains the following data:

readFile
textFile.txt

Then, we can read the data of this file as shown:

C++
#include <bits/stdc++.h> using namespace std;  int main() {      // Open the text file named      // "textFile.txt"     ifstream f("textFile.txt");      // Check if the file is      // successfully opened     if (!f.is_open()) {         cerr << "Error opening the file!";         return 1;     }     string s;      // Read each line of the file, store     // it in string s and print it to the     // standard output stream      while (getline(f, s))         cout << s << endl;      // Close the file     f.close();     return 0; } 


Output

Hey Geek! Welcome to GfG. Happy Coding.

Read From a Binary File

Binary files in C++ are used to store data in the binary form 0s and 1s. To read the data fo binary file, we need to open the input file stream (ifstream) object with the std::ios::binary flag. The getline() function cannot read the data from the binary files so we use the specialized function read() of ifstream class that reads the given block of data from the file stream and return it as a character array which can be converted to the required type using reinterprit_cast.

Syntax of read()

C++
stream.read(buffer, size) 

where,

  • stream: A valid ifstream object to binary file.
  • buffer: Pointer to the character array where the read data is to be stored.
  • size: Number of bytes to read.

Example

Consider the binary file contains the following data:

writeBinary
fileBin.bin

We can read this file as shown:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string str;      // Open the binary file for reading     ifstream file("fileBin.bin", ios::binary);     if (!file) {         cerr << "Error opening file for reading.";         return 1;     }      // Read the length of the string (size)     // from the file     size_t strLength;     file.read(reinterpret_cast<char*>(&strLength),         sizeof(strLength));      // Allocate memory for the string      // and read the data     // +1 for the null-terminator     char* buffer = new char[strLength + 1];       file.read(buffer, strLength);      // Null-terminate the string     buffer[strLength] = '\0';      // Convert the buffer to a string     str = buffer;      // Print file data     cout << "File Data: " << str;     delete[] buffer;          // Close file     file.close();     return 0; } 


Output

File Data: Welcome to GeeksForGeeks

One thing we can infer from here is that you need to know about the format or type of the contents stored in the binary file to successfully read it. It is not true for text file though, as we can read everything present in it as character.


Next Article
How to Read Data from a CSV File to a 2D Array in C++?

S

shakirradfcz
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-file-handling
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • How to Read and Write Arrays to/from Files in C++?
    In C++, an array is a collection of elements of the same type placed in contiguous memory locations. A file is a container in a computer system for storing information. In this article, we will learn how to read and write arrays to/from files in C++. Example: Input: Array = {1, 2, 3, 4, 5}Output: //
    2 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 Data from a CSV File to a 2D Array in C++?
    A comma-separated value file also known as a CSV file is a file format generally used to store tabular data in plain text format separated by commas. In this article, we will learn how we can read data from a CSV file and store it in a 2D array in C++. Example: Input: CSV File = “data.csv” //contain
    3 min read
  • How to Read a File Using ifstream in C++?
    In C++, we can read the contents of the file by using the ifstream object to that file. ifstream stands for input file stream which is a class that provides the facility to create an input from to some particular file. In this article, we will learn how to read a file line by line through the ifstre
    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
  • C++ Program to Make a File Read-Only
    Here, we will build C++ Program to Make a File Read-Only using 2 approaches i.e. Using ifstreamUsing fstreamC++ programming language offers a library called fstream consisting of different kinds of classes to handle the files while working on them. The classes present in fstream are ofstream, ifstre
    2 min read
  • 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 Open and Close a File in C++?
    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 fst
    2 min read
  • How to Get the MD5 Hash of a File in C++?
    In cryptography, we use the MD5 (Message Digest Algorithm 5) hash function for creating a 128-bit hash value which is represented as a 32-character hexadecimal number. However, this algorithm is not very secure cryptographically but can be used for file verifications, checksums, and ensuring data in
    5 min read
  • How to Read Input Until EOF in C++?
    In C++, EOF stands for End Of File, and reading till EOF (end of file) means reading input until it reaches the end i.e. end of file. In this article, we will discuss how to read the input till the EOF in C++. Read File Till EOF in C++The getline() function can be used to read a line in C++. We can
    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