0

Using C++, gcc.9x, Linux. I try to open and read file and then keep it opened for further operation - rewrite it for each iteration. But each time, after I do open this file - it gets wiped out. Is it possible to keep file content until I rewrite it ? And I want to keep file opened for writing all the time.

constructor()
{
    {
        ifstream tmp("file.db");
        int date;
        tmp >> date;
    }

    // it gets wiped out here, but I don't want it. 
    // And I want to keep ofstream opened all the time.
    fileStreamMember_.open("file.db");  // std::ofstream
}


writeMethod()
{
    fileStreamMember_.seekp(0, ios::beg);
    fileStreamMember_<< date_ << endl;
}
Alexandr Derkach
  • 584
  • 5
  • 15
  • 1
    Does this answer your question? [How to append text to a text file in C++?](https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c) – Pranav Hosangadi Apr 12 '21 at 14:37
  • Almost perfect duplicate: https://stackoverflow.com/q/39256916/103167 – Ben Voigt Apr 12 '21 at 14:51
  • Also https://stackoverflow.com/q/57069930/103167 – Ben Voigt Apr 12 '21 at 14:53
  • Thanks, it exmplains my issue. I need to override the file content each time. but it should exist, until I rewrite it... i tried to combine different flags - but it does not work for me. it either trunc file or appends to the end of the file.. – Alexandr Derkach Apr 12 '21 at 17:15
  • @AlexandrDerkach: The only one that lets you rewrite arbitrary places in the existing content is `in | out`. From your perspective you aren't reading existing content, but from the OS perspective if you want to change just a few bytes inside a block, the OS must read the block, change those bytes, and send the whole modified block back to disk. – Ben Voigt Apr 12 '21 at 20:47

2 Answers2

0

1-st: File objects have state. State is updated after each operation. You can use code like:

if (!fileStreamMember_) {
  // There is an error after operation
}

You can/should check state of file object during manipulations.

2-nd: You should close file object (or destroy it) to write all changes.

Evgeny
  • 721
  • 3
  • 5
  • I open file for reading in scope - it gets closed before the `open` call. Check for `!fileStreamMember_` won't help. I just want to preserve file content after opening it until i rewrite it. – Alexandr Derkach Apr 12 '21 at 17:18
  • Alexander, you should use right option at file opening. For example, try this:open("file.db", std::ios_base::out | std::ios_base::binary | std::ios_base::app); – Evgeny Apr 13 '21 at 08:47
0

std::ofstream open() function (and constructor) has a default flag of trunc. You should specify the flags/mode parameter explicitly or use std::fstream instead.

Ben Voigt
  • 260,885
  • 36
  • 380
  • 671