引言
最近学习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
文件流初始为空,写文件后,只有写的内容,所以才会造成清空原文件的现象