How can I open a file in c++, without erasing its contents and not append it?

本小妞迷上赌 提交于 2020-01-16 08:46:11

问题


I am trying to find a way using which I can Edit the contents in a binary file, without reading the whole file.

Suppose this is my file

abdde

And I want to make it

abcde

I tried following:- Attempt 1)

ofstream f("binfile", ios::binary);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(2,ios::beg);
  f.write(d, 1);
  f.close();
}
//the file get erased

Output:

**c

Attempt 2)

ofstream f("binfile", ios::binary | ios::app);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(2,ios::beg);
  f.write(d, 1);
  f.close();
}
//the file simple gets append seekp() does nothing

Output:

abddec

Attempt 3)

ofstream f("binfile", ios::binary | ios::app);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(2);
  f.write(d, 1);
  f.close();
}
//same as before the file simple gets append seekp() does nothing

Output:

abddec

And if I just try to replace the 1st byte of the file, which is 'a' with 'h'

ofstream f("binfile", ios::binary);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(ios::beg);
  f.write(d, 1);
  f.close();
}
//file is erased

Output:

h

What do I do? Is it even possible for the OS to allow a program to edit a file at any point own its own?


回答1:


std::ios::app means the cursor is put at the end of the file before every write. Seeking has no effect.

Meanwhile, std::ios::binary goes into "truncation" mode by default for an output stream.

You want neither of those.

I suggest std::ios::out | std::ios::in, perhaps by just creating a std::fstream fs(path, std::ios::binary) rather than using an std::ofstream.

Yes, it's a bit confusing.

(Reference)



来源:https://stackoverflow.com/questions/59059486/how-can-i-open-a-file-in-c-without-erasing-its-contents-and-not-append-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!