Wednesday, 25 November 2009

Input/Output with files

The following is a simple program to show reading, writing and appending to files. You can read more about this feature at cplusplus.com.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <fstream>
#include <string>

using namespace
std;

int
main()
{

string line;
cout<<"\nFile 1 operations - Writing to Hello.txt"<<endl;
ofstream file1; //OUTPUT file Stream
file1.open("Hello.txt"); //Open the file
file1 << "Writing something something to a file"<<endl;
file1 << "This is enough for the time being"<<endl;

if
(file1.is_open()) //Check if open
{
/*
while (!file1.eof())
{
getline (file1,line); - NOT POSSIBLE because of ofstream
cout << line << endl;
}
*/

}

file1.close(); //Close file1

cout<<"\nFile 2 operations - Reading from Hello.txt"<<endl;
ifstream file2; //INPUT file stream
file2.open("Hello.txt"); //Open the file
if(file2.is_open()) //Check if open
{
while
(!file2.eof())
{

getline (file2,line);
cout << line << endl;
}
}

file2.close(); //Close file2


cout<<"\nFile 3 operations - Appending and Reading from Hello.txt"<<endl;
fstream file3; //INPUT file stream
file3.open("Hello.txt", ios::in | ios::out); //Open the file
if(file3.is_open()) //Check if open
{
//We want to put a new line at the end of the file
file3.seekp(0, ios::end);
file3 << "This is new line added file 3"<<endl;
//Now reset the file pointer to the start of the file
file3.seekg(0, ios::beg);
while
(!file3.eof())
{

getline (file3,line);
cout << line << endl;
}
}

file3.close(); //Close file3

return
0;
}








The output is as follows:

No comments:

Post a Comment