-
read and write to file
hi, i was trying to write data to the end of a data file. i first read till the end of file and THEN tried write to the file. it compiles while,reads well..but wont write the data :(
this is my code
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(void){
fstream myfile ("a.dat");
string line;
//read and go to end of file
while (! myfile.eof() ){
getline(myfile,line);
cout<<line<<endl;
}
/*write to file*/
char *line1="testing line1";
char *line2="testing line2";
myfile.write(line1,15);
myfile.write(line2,15);
}
hope some 1 can correct my error. thanx
-
Don't use pointer to characters, use std::string s.
Code:
std::string line1 = "testing line 1";
myfile << line1;
-
also don't use eof to control a loop - check the return value of getline instead (see FAQ on File IO)
Also you need to clear the fail state before writing...