Questions about file operations (<iostream>)

Hi,

As the the title say, this is a question about file operations in <iostream>. Say outfile contains "abc", the following

ostream out = ofstream({outfile file path});
out << xyz

Will result in outfile's content to be changed to "xyz". Is there a simple way to insert stuff either at the beginning or end of a file without deleting what it contains? i.e. how do I turn outfile from "abc" to "xyz\nabc" or "abc\nxyz"?
Yes, it is simple, but no, there is no magic "insert" or "delete" function.
You have to do one of the following:

A. (simplest)
Read the entire file into memory.
Make changes.
Write the entire file to disk.

B. (less simple)
Open file for input.
Open temp file for output.
Copy file to temp, making changes as you go.
Close both files.
Delete source file.
Rename temp file to source file.

Variations on a theme.

Hope this helps.
Some help for A:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

bool read_file( const string& filename, vector <string> & filedata )
  {
  ifstream f( filename.c_str() );
  string s;
  while (getline( f, s ))
    filedata.push_back( s );
  return f.eof();
  }

Good luck!
Thanks for your reply. I will look into that code. But quick question, what does "&" stand for in "const string& filename"?
Topic archived. No new replies allowed.