C++文件读取操作详解

本文详细介绍了C++中ifstream、ofstream和fstream类的文件读取操作,包括文件打开方式、默认选项、流对象的打开与关闭、常用函数、流状态检测、流指针、读写方式以及缓存同步机制。重点讲解了不同打开模式的影响,如ios::app、ios::in、ios::out等,并探讨了二进制文件和文本文件的读写差异。
摘要由CSDN通过智能技术生成

图片来自:http://www.cplusplus.com/reference/iolibrary/
上面的C++ IO类继承关系图,这里的箭头不是子类指向父类的继承,而是指父类派生子类的方向。这里主要描述ifstream类/oftream类/fstream类的使用细节和这些类的系统内部同步缓存机制。

一、文件打开的方式和默认选项
// 附加到末尾,原来的数据不变
ios::app Opens an output file for appending.
// 文件打开后定位到文件尾,ios:app就包含有此属性
ios::ate Opens an existing file (either input or output) and seeks the end.//附加到末尾原来的数据会被清空(单独或与out组合),当与in或app组合时候会附加到末尾。
ios::in Opens an input file. Use ios::in as an open_mode for an ofstream file to prevent truncating an existing file.  
ios::out Opens an output file. When you use ios::out for an ofstream object without ios::app, ios::ate, or ios::in, ios::trunc is implied.
ios::nocreate Opens a file only if it already exists; otherwise the operation fails.
ios::noreplace Opens a file only if it does not exist; otherwise the operation fails.
ios::trunc Opens a file and deletes the old file (if it already exists).
ios::binary Opens a file in binary mode (default is text mode).

fstream默认是以ios::in|ios::out方式打开文件。
ifstream默认是以ios::in方式打开文件。
ofstream默认是以ios::out|ios::trunc方式打开文件,所以oftream一不小心就会覆盖掉之前的文件。

二、文件流对象打开文件(及内核缓存)和关闭文件(及内核缓存)
fstream有两个子类:i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值