2. Reading from a file #
Created Saturday 25 April 2020
- Reading to a file - unlike cin and cout, we have to create the objects similar to cin and cout.
- For writing, we need only the in file stream(ifstream) object.
- Include fstream - it has ifstream and ofstream inside
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
// provide the modes app, trunc - by default trunc is assumed
// create an object to handle the file
// the file must exist - we should check that it exists
ifstream infile; // infile points to the file, NULL if it does not exist
infile.open("my.txt"); //no need mention flag/mode, coz ifstream is for reading only
// check or check if(infile)
if(infile.is_open()) // returns ifFileExists
cout << "Exists\n";
else
cout << "Doesn't Exist\n";
// printing the file to console
string x = "";
infile >> x; // assuming we know the format and the encoding
cout << x; // infile pointer moves forward, jumps at whitespaces
// for checking if file has ended
if(infile.is_eof())
cout << "File Ended";
// for reading the whole/part file
while(infile.good())
{
infile >> x;
cout << x;
}
//closing the file - very important
infile.close(); // it's free now - i.e the OS knows that we have freed the file for other programs
return 0;
}