C++的文件操作
文件操作的类
ofstream //文件写操作,从内存写入存储设备
ifstream //文件读操作,从存储设备读到内存中
fstream //读写操作,对打开对象进行读写操作
eg:
ifstream file;
file.open(const char* filename,int mode,int access);
file.close();
参数access可以不填。缺省值是0,代表 普通文件。
参数mode有:
ios::in | 为输入(读)而打开的文件 | ios::out | 为输出(写)而打开的文件 |
---|---|---|---|
ios::ate | 初始位置:文件尾 | ios::app | 所有输出附加在文件尾 |
ios::trunc | 文件不存在产生错误 | binary | 二进制方式 |
ios::nocreate | 文件不存在产生错误 | ios::noreplace | 文件存在产生错误 |
.
上面选项可以用 | (或)来混合使用。
文件读写
file << "I am here" //写入
file >> (char)data //读取 (后面数据可以有数据类型,eg:int i ; file >> i; 读取一个整数)
重构的赋值符号“<<”、“>>”可以格式化
dec | 十进制 |
---|---|
endl | 输出换行 |
ends | 输出空字符 |
hex | 十六进制 |
oct | 八进制 |
setpxecision(int p) | 浮点位精度位数 |
.
eg:
file << hex << 123 //十六进制写入
file << setpxecision(5) << 3.141592 //保留5位小数
二进制读写
ofstream &put(char ch); //eg: file.put('a');向文件写入一个字符
ifstream &get(char *ch); //有三种重载方式
/*
1. ifstream.get(char *ch);//读取一个字符到ch
2. (char) date = ifstream.get();//功能同上,但读到文件末尾返回EOF
3. ifstream.get(char *buf, int num)
*/
write ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );
// buffer是传入的缓存地址,size是读、写多少个字节(二进制)。
文件指针定位
ifstream &tellg();
ofstream &tellp();
//返回pos_type 类型(整数),代表当前get 流指针的位置 (用tellg) 或 put 流指针的位置(用tellp).
.
ifstream &seekg ( off_type offset, seekdir direction );
ofstream &seekp ( off_type offset, seekdir direction );
//off_type 表示整数的位移,seekdir 表示从哪儿开始
seekdir的枚举类型 | |
---|---|
ios::beg | 文件开头 |
ios::cur | 文件当前位置 |
ios::end | 文件结尾 |
eg:
file.seekg(0,ios::beg); //定位文件开头
.
状态标准符的验证
bad(); //若在读写状态下出错,返回true
fail();//除和上面相同,还有个事错误返回true,如读整数而获得字符的时候
eof();//文件读到末尾,返回true
good();//最通用,若调用以上任何一个函数返回true,它返回false.可以用在文件是否正确打开
claer();则用来清除标志位,也可以用于输入,输出转换。以有一个例子。
eg:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
char data[100] = {'\0'};
char data1[100] = {'\0'};
fstream file;
file.open("/tmp/test", ios::out | ios::in | ios::app);
cout << "please type something in here!\n";
cin.getline(data, 100);
file << data;
cout << "--------" << endl;
file.clear(); //清除文件标准为,转换为输入
file.seekg(0,ios::beg); //将文件指针放回最前面
file >> data1 ;
cout << data1 << endl;
file.close();
return 0;
}
结果,我在/tmp/test/事先存了abcd。
please type something in here!
helloworld
--------
abcdhelloworld
更多文件操作函数,可查询 fstream 类的库。