Posted By:
4 Jul, 2013 1:34 pm PDT

Reading and writing of text files in C++

How to read data from a text file? How to write data onto a text file?
Attachment:None


Text file streams are those where we do not include ios::binary flag in their opening method. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations Data input/output operations on text files are performed in the same way we operated with cin/cout. For Example: 

// writing on a text file
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream fn;
fn.open(“example.txt”);
if(fn.isopen())
{
fn<<”Hi, this is a line”;
fn<<”Hello World”;
fn.close();
}
else
cout<<”Unable to open the file”;
}

/* There won't be any output but a text file named example will be created */

See the following code for reading a text file:

 

//reading a text file

#include<iostream.h>
#include<fstream.h>
void main()
{
char a[20];
ifstream fn;
fn.open(“example.txt”);
while(!fn.eof())
{
getline(fn,a);
cout<<a<<endl;
}
fn.close();
}

In the above example we have used eof().

eof() returns true in the end of the file is reached.

Attachment: file1.cpp
Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud