背景:想在文件中间任意位置插入任意字符 现象:总是加在文件末尾
#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](
我的解答思路和尝试过的方法
为了证明指针位置确实改变了,尝试从指针位置开始读取,验证指针确实改变了
是什么影响了写呢
我想要达到的结果
在中间写入即可,不管是覆盖还是插入