Jan 30, 2009

Input and output file handling in C++

The most frequent thing open a file with path name goes like this.

#include < fstream.h >

Current directory.
ofstream fout("TAtesting.txt");

Inside a folder of the current directory.
ofstream fout("Release/TAtesting.txt");


For 1 level up the current directory.
ifstream fin("..//..//TAtestingInput.rtf");


For 2 level up the current directory.
ifstream fin("..//..//TAtestingInput.rtf");

With path name specified.
ifstream fin("/Users/reza/Documents/workspace/TAtestingInput.rtf");


Same is true for output file.
ofstream fout("TAtestingOutput.txt");

To check whether the file is opened correctly.
cout<<"File is open "<< boolalpha<< fin.is_open()<< endl;

To write something inside the file instead of cout name of the file in the code.
fout<<"Here is something for the file as an output."<< endl;

Finally to close the file.
fin.close();
fout.close();

1 comment:

Hitesh Kumar said...

File Handling in C++

File Handling concept is mainly used for store data permanently system or computer. Using file handling we can store our data in Secondary memory (Hard disk).