2. Reading from a file #

Created Saturday 25 April 2020

#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;
}