How can i edit a txt file without deleting the content in c++?

253 Views Asked by At

I want to create a database in a txt file and access it and edit certain parts of it using seekp(), but when I open the file to write in it , the program creates a new file deleting the previous one.


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

int main() {

    ofstream g;
    g.open("text.txt",ios::out);
    if(!g.is_open())
        cout<<"error";
    else {
        g.seekp(2);
        g.write("apple",5);
    }
    g.close();

    return 0;
}
1

There are 1 best solutions below

3
Cee McSharpface On

You'll need a different open mode.

The documentation is quite obscure when it comes to the behavior of ofstream (for all practical purposes, the behavior you observe is by design: it will truncate).

Use fstream with ios_base::in | ios_base::out | ios_base::binary instead.

Unless you're using some encoding where one character is always one, two, or four bytes, you won't be able to consistently do this with a text mode. Also, writing at any seek position before end-of-file won't shift content past the current seek position, it is simply overwritten. So in order to achieve a database-like behavior, you're at least going to need some kind of fixed-size records or an indexing data structure.