Open In App

How to Read a File Character by Character in C++?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to illustrate how to read a file character by
// character
#include <fstream>
#include <iostream>
using namespace std;
  
int main()
{
    // Open the file
    ifstream file("example.txt");
  
    // Check if the file was opened successfully
    if (!file) {
        cout << "Unable to open file";
        return 1;
    }
  
    // Read the file character by character
    char ch;
    while (file.get(ch)) {
        cout << ch << " ";
    }
    cout << endl;
  
    // Close the file
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads