How to Read a File Character by Character in C++?
Last Updated :
06 Mar, 2024
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 s
Read Text from a File Character by Character in C++
To read a file character by character in C++, we can make use of the ifstream class to create an input stream from the file and then use the ifstream::get() function which sets the given variable to the current character read from a file.
Approach
- We will declare a variable called file with the help of ifstream class and pass the path of the file to it.
- Now first we will check if the file got read or not.
- If not then we will print an error while opening the file.
- If the file is opened successfully then we will iterate over the file till the ifstream::get() function returns NULL.
- While iterating, we will print each character one by one.
C++ Program to Read a File Character by Character
C++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream file( "example.txt" );
if (!file) {
cout << "Unable to open file" ;
return 1;
}
char ch;
while (file.get(ch)) {
cout << ch << " " ;
}
cout << endl;
file.close();
return 0;
}
|
Output
G e e k s f o r G e e k s
Time complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...