marchent
asked on
fstream read and write problem
i want to write read/write both using fstream, no ifstream/ofstream. here is what i'm trying
string s;
fstream file("test.txt");
file>>s;
cout<<s; //to console
file<<s;
file.flush();
file.close();
it is reading from file, but not writing, can u fix my problem here?
string s;
fstream file("test.txt");
file>>s;
cout<<s; //to console
file<<s;
file.flush();
file.close();
it is reading from file, but not writing, can u fix my problem here?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Your last comment does not match your "here is what I'm trying" from original question.
Can you please post EXACTLY what you are trying to do, please :)
Can you please post EXACTLY what you are trying to do, please :)
I think this what you are looking for, reading and writing file with only one open. Notice the file is opened specifing both input and output.
#include <fstream.h>
int main(int argc, char* argv[])
{
char s[2046];
fstream file;
file.open("C:\\Test\\Test File 1.txt", ios::out | ios::in);
long beginfile = file.tellp(); // get the beginning of file position
file << "data\n"; // write some data
file << "more data"; // write more data
long endfile = file.tellp(); // get the end of file position
file.flush(); // flush the buffer
file.seekg(beginfile); // go to beginning of file
file.get(s, 5); // read 4 chars and a null into s
cout << s << endl; // print it out
file << s; // write those 4 chars after the four we just read
file.seekg(endfile); // go to what was the end of file
file << s; // write those 4 chars again
file.close(); // close the file
return 0;
}
The file contents look funky now!
#include <fstream.h>
int main(int argc, char* argv[])
{
char s[2046];
fstream file;
file.open("C:\\Test\\Test File 1.txt", ios::out | ios::in);
long beginfile = file.tellp(); // get the beginning of file position
file << "data\n"; // write some data
file << "more data"; // write more data
long endfile = file.tellp(); // get the end of file position
file.flush(); // flush the buffer
file.seekg(beginfile); // go to beginning of file
file.get(s, 5); // read 4 chars and a null into s
cout << s << endl; // print it out
file << s; // write those 4 chars after the four we just read
file.seekg(endfile); // go to what was the end of file
file << s; // write those 4 chars again
file.close(); // close the file
return 0;
}
The file contents look funky now!
I think my above example has an error in it; you should use seekp (not seekg) to move the "put" pointer. seekg changes the "get" pointer. Sorry!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER