Pages

Tuesday, October 18, 2011

Reading a complete file using get()

Reading the whole file using get()

The get() can not read more than one character at a time , therefore we must use a loop to read the file. The while loop is most suitable for reading a file since we don't know how much data is there in the file.

#include "conio.h"
#include "iostream.h"
#include "fstream.h"
void main()
{
 clrscr();
 ifstream in("file1.txt");
 char c;
 in.get(c);
 while(in)
 {
  cout<<c;
  in.get(c);
 }
 in.close();
}

Output (Assuming that the file contains a word "Welcome")
Welcome

The while loop will run as long as the file contains the data. The get() function will read all the contents of the file till the its end.

0 comments:

Post a Comment