Hello,

ostream - how to insert a line of text instead of overwrite in the beginning of the file?

#include <fstream.h>
int main()
{
char fileName[] = "SampleFile";
char buffer[255];
ofstream m_fp;
// m_fp.open(fileName, ofstream::ate );
m_fp.open(fileName, ios::in|ios::out);
m_fp.seekp(0, ios::beg );
m_fp << "This is the line written to the file 01"<<endl;
m_fp.close();
};

SampleFile has:
11111111111111111
2222222222222222
3333333333333333
44444444444444444
5555555555555555555555

When this progrom get executed, I got:
This is the line written to the file 01
33333333333
44444444444444444
5555555555555555555555

How can I get output like this?

This is the line written to the file 01
11111111111111111
2222222222222222
33333333333
44444444444444444
5555555555555555555555


Thanks,
Jeff

I'm certain there is a FAQ about this. The only way to do that is to rewrite the entire file. Read the whole file into memory then write it back out the way you want it. If the file is too big to read into memory all at once you can use a temporary file.

It's my understanding that ::ate places you at the end of the file and allows you to write data anywhere in the file, however, writing to a specific location overwrites what was previously there.. I believe you use seek() or something with that method, but I doubt that's what you're looking for. If you want to append to a file (not at the end) and preverse what was previously there then it's impossible. Go with what AG said.

Yah...you have to read it all in first...you could use this read funciton which reads it all in at once instaed of using mutlistrings or something...but usually i just add things in one line at a time...take 2 strings...

1. Make string one your original msg to insert
2. Read in the first line to string2
3. Insert string 1 (string with orignal msg)
4. Move string 2 to string 1
5. Repeat starting at step 2 until entire file copied (good time for a loop)

Thanks for help, it is good idear. I will try that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.