Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to perform read operation in the file

C++ Code Example — File Handling Programs

ADVERTISEMENT

WAP to perform read operation in the file

Objective

Write a C++ program to perform a read operation from a file.

Algorithm / Approach

  1. Create an object of ifstream (Input File Stream).
  2. Read the filename and open it using in.open(name, ios::in).
  3. Check if the file opened successfully using if(!in).
  4. Run a loop until the End of File is reached: while(in.eof() == 0).
  5. Read characters one by one using in.get(c) and print them to the screen.
  6. Close the file.
main.cpp
#include<iostream>
#include<fstream>
using namespace std;
class Test {
 public:
 void read() {
  char c;
  char name[10];
  ifstream in;
  cout<<"Enter File Name: ";
  cin.getline(name,10);
  in.open(name,ios::in);
  if(!in){
   cout<<"File doesn't exists";
  }
  else {
   while(in.eof()==0) {
    in.get(c);
    cout<< c;
   }
  }
  in.close();
 }
};
int main() {
 Test t;
 t.read();
 return 0;
}

Expected Output

Enter File Name: apps.txt
Developed for Beginners

Explanation of the Program

  • ifstream stands for Input File Stream. It is used exclusively for reading existing files.
  • The eof() (End of File) function is critical when reading files. It returns true when the stream attempts to read past the very last byte of the file, allowing our loop to gracefully stop reading.

Complexity

Time Complexity O(n) - Where n is the file size in bytes.
Space Complexity O(1)
ADVERTISEMENT