c++ fstream库操作文件,关于std::ios::out、std::ios::in、std::ios::trunc理解

引言

最近学习c++ 文件操作,使用fstream库操作文件时,因为打开模式不同,产生的结果很奇怪,比如如下几种场景

问题原因在网上搜了很久也没找到,最后根据结果自己得出了一个结论。如有问题,希望大佬们指正

实验

初始有一个fstream.txt文件,文件内容如下

line 1 Hello World !
line 2 Hello World !
line 3 Hello World !

1. 执行如下代码,只以 out 模式打开文件并写入  line 4 Hello World !,输出如下

#include<iostream>
#include<fstream>

int main() {
    std::fstream file;
    file.open("fstream.txt", std::ios::out);
    file << "line 4 Hello World !" << std::endl;
    return 0;
}

最终文件内容如下:
line 4 Hello World !

这让我产生一个问题,我没有以trunc模式打开文件,为什么原文件内容清空了?

2. 随后执行如下代码,以 out 和 in 模式打开文件并写入  line 4 Hello World !,输出如下

#include<iostream>
#include<fstream>

int main() {
    std::fstream file;
    file.open("fstream.txt", std::ios::out | std::ios::in);
    file << "line 4 Hello World !" << std::endl;
    return 0;
}

最终文件内容如下:
line 4 Hello World !
line 2 Hello World !
line 3 Hello World !

 可以看到这才是我期望的输出,原文件内容保留,写入的内容只覆盖原文件开头部分

3. 再执行如下代码,以 out 和 in 和 trunc 模式打开文件并写入  line 4 Hello World !,输出如下

#include<iostream>
#include<fstream>

int main() {
    std::fstream file;
    file.open("fstream.txt", std::ios::out | std::ios::in | std::ios::trunc);
    file << "line 4 Hello World !" << std::endl;
    return 0;
}

最终输出结果如下:
line 4 Hello World !

可以看到原文件内容因为以 trunc 模式打开而清空了

结论

不管是读文件还是写文件,最后都是用当前文件流替换文件内容

    1. std::ios::out | std::ios::in

    此时文件流有原文件内容,写文件后,从原文件开头覆盖(其余部分保留)

    2. std::ios::out | std::ios::in | std::ios::trunc

    trunc清空了文件流中原文件内容,写文件后,只有写的内容,原文件内容消失

    3. std::ios::out

    文件流初始为空,写文件后,只有写的内容,所以才会造成清空原文件的现象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值