Opening a File for writing and reading

G

Giulio

I'm dealing with a log management program: I must save some records to a
file... and occasionally read previously written records.
because it's a log file, all the writes will be at the end of the file.

for studying this problem I made the following example program.

It works in a very strange way:
every time it open the file it copies the last char. i.e. if the first time
the file contains "home" second time I execute the prog it will contain
"homee".
then I have problems in seeking inside the file.

could anyone help me solve this problem??

thanx alot
Giulio

----------------------------
#include <fstream>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{
fstream File("test.txt",ios_base::eek:ut|ios_base::in );
if (File.fail() ) { cout << "errore in apertura"; system ("pause");
exit( 1);}
// File << "a \n asd";
File.seekg(ios_base::beg);
do{
string str2;
File >> str2;
cout << "'" << str2 << "'" << endl;
}while(!File.eof());
cout << "lettura 1"<< endl;
cout << "tellp : "<<File.tellp()<< endl;
cout << "tellg : "<<File.tellg()<< endl;

File.seekp(ios_base::end);
cout << "scrittura 1"<< endl;
cout << "tellp : "<<File.tellp()<< endl;
cout << "tellg : "<<File.tellg()<< endl;
File << "ultima" << endl;

cout << "-------------------------------";
cout << "lettura "<< endl;
cout << "tellp : "<<File.tellp()<< endl;
cout << "tellg : "<<File.tellg()<< endl;


File.seekg(ios_base::beg);
do{
string str2;
File >> str2;
cout << "'" << str2 << "'" << endl;
}while(!File.eof());
cout << "tellp : "<<File.tellp()<< endl;
cout << "tellg : "<<File.tellg()<< endl;

File.close();
system ("pause");
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top