How to Read From a File in C++?
Last Updated :
12 May, 2025
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 in the form of text (characters).
- 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:
textFile.txtThen, 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:
fileBin.binWe 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.
Similar Reads
How to Read Binary Search Tree from File in C++? A binary search tree is a hierarchical data structure in which for every node in the tree, the value of all nodes in the left subtree is less than the node's value and the value of all nodes in the right subtree is greater than the node's value. This property of the binary search tree makes it effic
4 min read
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 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