How to write some data into a file without erasing the original content

The description of the problem

I was ready to replace some data in a file and I also hope the original content has been conserved.

The first try and its failures

The codes

#include <iostream>
#include <fstream>

int main()
{
    // test std::ios::ate
    std::ofstream ofs("test.txt");
    ofs << "Hello, World!" << std::endl;
    ofs << "Hello, World!" << std::endl;
    ofs.close();
    // write 'B' to replace the first character in the test.txt without erasing the content
    std::ofstream ofs_2("test.txt", std::ios::binary);
    ofs_2.seekp(0, std::ios::beg);
    ofs_2.write("B", 1);
    ofs_2.close();


    return 0;
}

The corresponding results

在这里插入图片描述

It is easy to find that when you use another object of ofstream to open a file, it will clear all the original content.

The second try

I just found that when you add std::ios::app, the original content will be conserved.
However, the problem is the seekp() will be useless.

correlated codes

#include <iostream>
#include <fstream>

int main()
{
    // test std::ios::ate
    std::ofstream ofs("test.txt");
    ofs << "Hello, World!" << std::endl;
    ofs << "Hello, World!" << std::endl;
    ofs.close();
    // write 'B' to replace the first character in the test.txt without erasing the content
    std::ofstream ofs_2("test.txt", std::ios::binary|std::ios::app);
    ofs_2.seekp(0, std::ios::beg);
    ofs_2.write("B", 1);
    ofs_2.close();


    return 0;
}

corresponding results

Hello, World!
Hello, World!
B

The final solution

just add read mode into your object attributes

The related codes

Bello, World!
Hello, World!

Good luck

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值