WAP to perform read operation in the file
Objective
Write a C++ program to perform a read operation from a file.
Algorithm / Approach
- Create an object of
ifstream(Input File Stream). - Read the filename and open it using
in.open(name, ios::in). - Check if the file opened successfully using
if(!in). - Run a loop until the End of File is reached:
while(in.eof() == 0). - Read characters one by one using
in.get(c)and print them to the screen. - 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
ifstreamstands 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)