5

I have a text file where I want to write. I want to keep the file content always. I want to write following a "FIFO" (last write always on the top line of the file).

I try using fout.open("filename"); with ate mode to keep file content, after that use seekg(0) trying to take back writing cursor to the begining of the file. Didn't work.

The unique way I found to do that I think it's so time-expensive, copy all the file content to a temporary file. Write want I want to write and after that write the content of the temp file at the end of the target file.

There must be an easy way do this operation?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Jorge Vega Sánchez
  • 7,430
  • 14
  • 55
  • 77

5 Answers5

5

Jorge, no matter what you will have to rewrite the entire file in memory. You cannot simply keep the file where it is and prepend memory, especially since it's a simple text file (maybe if there was some form of metadata you could...)

Anyways, your best chance is to flush the old contents into a temporary location, write what you need and append the old contents.

Constantin
  • 16,812
  • 9
  • 34
  • 52
1

I'm not sure what you're asking for. If you want to add a line to the beginning of the file, the only way is to open a new, temporary file, write the line, copy the old file into after the new line, then delete the old file and rename the temporary.

If the original line has a fixed length, and you want to replace it, then all you have to do is open the file with both ios_base::in and ios_base::out.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
0

First, you should realize that files are historically streams, i.e. they can only be read and written in one direction. This comes from the times when files were stored on tapes, which could move in one direction (at that time).

However, if you only want to prepend, then you can just store your file backwards. Sounds silly? Maybe, but this would work with just a little overhead.

Apart from that, with current OS's you will need to make a copy to prepend. While files are not streams anymore, and can be accessed randomly on a harddisk, they are still made to grow in one direction. Of course you could make a filesystem, where files grow in both directions, but I have not heard of one.

Zane
  • 926
  • 8
  • 21
0

With <fstream> you may use the filebuf class.

    filebuf myfile;
    myfile.open ("test.txt", ios::in | ios::out);
    if (!myfile.is_open()) cout << "cannot open" << endl;
    myfile.sputn("AAAA", 4);
    myfile.close();

    filebuf myfile2;
    myfile2.open ("test.txt", ios::in | ios::out);
    if (!myfile2.is_open()) cout << "cannot open 2" << endl;
    myfile2.sputn("BB", 2);
    myfile2.close();
Adrian Maire
  • 14,354
  • 9
  • 45
  • 85
-4

write to a string in order you want, then flush to the file

iddqd
  • 193
  • 1
  • 1
  • 5