图片来自: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