文件操作:任意位置写入

背景:想在文件中间任意位置插入任意字符 现象:总是加在文件末尾
#include       // std::ifstream, std::ofstream
#include 
using namespace std;
int main() {

    std::fstream outfile/*("new.txt", std::ofstream::binary | std::ofstream::app)*/;
    outfile.open("new.txt", fstream::binary | fstream::out | fstream::app | fstream::in/*ios::app*//* ios::out | ios::ate | ios::binary, _SH_DENYNO*/);

    char* buffer_0 = new char[50];
    if (outfile.is_open()) {
        outfile.seekp(3, ios::beg);
        //读没问题,是按照指针在的位置开始读取的
//         outfile.read(buffer_0, 50);
//          for (int i = 0; i < 50; ++i) {
//              std::cout << *(buffer_0 + i);
//          }
//         std::cout << std::endl;
        //为什么写有问题
        outfile.write("c", 2);
        outfile.close();
    }

    delete[] buffer_0;
    return 0;
}
运行结果及报错内容

222
55
333
33
4c
![img](

我的解答思路和尝试过的方法

为了证明指针位置确实改变了,尝试从指针位置开始读取,验证指针确实改变了
是什么影响了写呢

我想要达到的结果

在中间写入即可,不管是覆盖还是插入

盲猜是 fstream::app 导致的写入内容追加到末尾

binary|out|in|app打开模式等价于用"a+b"模式调用fopen()函数,写入数据是写入到文件结尾。
如果你想在任意位置写入字符,你去掉app

https://en.cppreference.com/w/cpp/io/basic_filebuf/open

img