C++ 文件流

C++ 文件流示例

类名 基类 描述
ofstream ostream 文件输出
ifstream istream 文件输入
fstream iostream 文件输入输出

公共方法

检测本身值为 0 时表示文件结束。

方法名 描述
open(const unsigned char *, int mode, int access=filebuf::openprot) 打开文件
close() 关闭文件
int gcount(); 返回 read/write 的字节数
int eof(); 返回非零表示文件结束

ofstream 对象

方法名 描述
ostream &put(char ch) 写字符
ostream &write(const unsigned char *, int num) 写 num 字节
ostream &seekp(streamoff off, ios::seek_dir dir) 指针定位

ifstream 对象

方法名 描述
istream &get(unsigned char &ch) 读字符
istream &read(unsigned char *, int num) 读 num 字节
istream &seekp(streamoff off, ios::seek_dir dir) 指针定位

open 方法

open(const unsigned char *, int mode, int access=filebuf::openprot)
参数 描述
const unsigned char * 文件名
int mode 打开模式,多属性用或操作连接
int access 存取方式

mode

常量 描述
ios::app 输出文件尾,文件必须存在
ios::ate 查找文件尾
ios::in 打开文件读
ios::nocreate 文件必须存在
ios::noreplace 文件必须不存在
ios::out 打开文件写
ios::trunc 替换同名文件
ios::binary 二进制方式打开

access

常量 描述
0 普通文件
1 只读文件
2 隐含文件
4 系统文件
8 备份文件

seekdir

常量 描述
ios::beg 从文件头开始
ios::cur 从当前位置开始
ios::end 从文件尾倒数