Pages

Tuesday, October 18, 2011

Reading a file - char by char (using get())

The get() function

The get() can read a char from a file. It is used when we want to read a single character from a file. To read all the data of a file, the same function can be enclosed inside a loop.

Syntax
ifstream.get(char);

Example : Lets see the following code snippet that makes use of the "get()" to read a char from the file.

#include "conio.h"
#include "iostream.h"
#include "fstream.h"

void main()
{
 clrscr();
 ifstream in("file1.txt");
 char c;
 in.get(c);
 cout<<c;

in.close();
}


The above program will open a file named "file1.txt" in read mode using the ifstream class. Once the file is opened the "get()" will read a character from the file. Since a file always opens from the beginning, the code will read the first character of the file only.

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


0 comments:

Post a Comment