m0_37960188 2022-09-26 17:56 采纳率: 33.3%
浏览 31

文件操作:任意位置写入

背景:想在文件中间任意位置插入任意字符 现象:总是加在文件末尾
#include <fstream>      // std::ifstream, std::ofstream
#include <iostream>
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](

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

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

我想要达到的结果

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

  • 写回答

2条回答 默认 最新

  • Cpp你带我走吧 2022-09-26 18:26
    关注

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

    评论

报告相同问题?

问题事件

  • 创建了问题 9月26日