Sign in to follow this  

How to read/write to files in C++ without Overwriting

This topic is 3868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm currently trying to open a text file for reading and writing. I want to use fstream because I need to read AND write. However, I don't want to overwrite anything. I've seen all kinds of convoluted code that involves moving the cursor around, but I'm looking for something much simpler.
fstream infile (argv[1]);
string x;
while(getline(infile, x));
infile << "XXXXXXXXXXXXXx";

Does not write the X's to the end of the file. What am I doing wrong?

Share this post


Link to post
Share on other sites
iostreams have two cursors: one for reading, one for writing. The simplest and most intuitive way to write at the end of the file is to place the write cursor there:

stream.seekp(0,ostream::end);

Alternatively, you may create a file stream with the cursor already positioned at the end by using the app flag when opening the file.

Share this post


Link to post
Share on other sites
This is the closest I can get

string line;
ifstream fin("testFile");
ofstream fout("testFile", ios::app);
while(getline(fin, line));
fout << "XXXXXXXXXXXXXx";

Share this post


Link to post
Share on other sites
I managed to both read and write from a fstream object by poking into the filebuf member:


#include <fstream>
#include <iostream>
using namespace std;

int main()
{
char ch;
fstream filestr;
filebuf *pbuf;

pbuf=filestr.rdbuf();

pbuf->open("testFile", fstream::in | fstream::out);

while(pbuf->sgetc() != EOF)
{
ch = pbuf->sbumpc();
cout << ch;
}

pbuf->sputn("XXXXXXXXXX", 10);

pbuf->close();

return 0;
}



It seems to me though that using two different objects for reading and writing is a better way.
For some reason the operator << and >> does not work for the fstream object.
Maybe someone else knows more about that.

Share this post


Link to post
Share on other sites
You want to read from a file and write to another?

istream in("testFile", ios::app);
ostream out("outputfile.txt");
string x;
in >> x;
while(!in.eof()){
out << x;
}


Simplest thing I can think of


Share this post


Link to post
Share on other sites

This topic is 3868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this