Roy Gourgi wrote:
Hi,
How can I write to a file and then be able to read what I wrote to it later
on. I would like to save some information on to a file continuously and then
be able to retrieve that information later on when I need it. Also, what
headers, etc.... do I need to include in my file. Finally, if I want to find
and retrieve only specific information from the file that I wrote to (much
like a seek in a database program) how do it do it.
Thanks a lot in advance
Roy
Hi Roy,
Here's a simple exampel showing input and out put to a file:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// File to read and write to
ofstream outFile;
ifstream inFile;
// A small buffer for the reading
char buffer[256];
// We start by writing to the file
outFile.open("example.txt", ios::out | ios::app );
// Check whether the file is open
if(!outFile.is_open()){
cout << "Error opening file" << endl;
return 1;
}
// Lets write something to the file
outFile << "This is a line\n";
outFile << "This is another line\n";
// Done writing - lets close
outFile.close();
// Open the file for reading
inFile.open("example.txt");
// Check whether the file is open
if(!inFile.is_open()){
cout << "Error opening file" << endl;
return 1;
}
// Lets read that from the file
while(!inFile.eof()){
inFile.getline(buffer, 100);
cout << buffer;
}
// Remember to close the file
inFile.close();
return 0;
}
The part about seeking is a bit complicated, hopefully someone has a
good idea there..
--
// Morten -
www.mortenvp.dk