c++用于操作文件的类如下:
ofstream: 写文件(把数据从流中写出至文件中 , 对应 output)
ifstream: 读文件 (把数据从文件中读入流中, 对应 input)
fstream: 同时可以读写。
这三个类都直接或间接的继承于istream或ostream。我们经常使用的cin其中就是istream类的一个对象,cout则是ostream的对象。而关于文件操作流与cin或cout在使用基本相似,唯一不同的它们需要关联指定的文件。例如:
ofstream file;
file.open("test.txt");
file<<"hello ";
file<<"world ";
file<<"\n";
char str[100]={" \tthis is a test \n"};
file.write(str,strlen(str)*sizeof(char));
file.close();
文件的内容如下:
hello world
this is a test
需要注意,它这里支持换行符,而且每次都把文件中的内容清空再写入数据.
1 打开文件
用流打开文件,首先需要定义一个ifstream对象,然后调用它的open方法。open方法格式如下:
open(fileName,mode);
其中mode是一个可选项,可以由下表中标志位,可以通过“|”任意组合。
ios::in | 打开为读 |
ios::out | 打开为写 |
ios::binary | 二进制模式 |
ios::ate | ate == at the end of file,设置写或读的初始位置在文件的末尾。 如果没有设置这个标志,则都以文件头开始。 对于写操作,设置它将会清除以前的内容,并把新内容写入。 对于读操作,可以用于确定文件的大小。 |
ios::app | 写文件从文件末尾开始。(对于写操作,直接追加文件) |
ios::trunc | 如果文件打开为写操作且文件已经存在,则文件上一次的内容将被清除。 |
ofstream, ifstream, fstream 都有默认的mode值。
class | Default mode parameter |
ofstream | ios::out (默认都是如果文件不存在则建立,如果存在则清空内容重新写入) |
ifstream | ios::in |
fstream | ios::in | ios::out |
对于ofstream,ifstream不需要显示地指定ios::out或ios::in,因为它们会被自动的添加,所以可以直接地给其它标志位参数。如:(ios::out |ios::ate) == ios::ate。
但是fstream是不会自动添加的,会被传递的模式覆盖默认模式的。
可以通过调用is_open方法来判断文件是否打开成功。如:
if (myfile.is_open()) { /* ok, proceed with output */ }
2 关闭文件
确定文件结束的方法为eof(),如
eof() returns true if a file open for reading has reached the end.
关闭文件直接调用close方法即可。
3 读文件
这里文本文件为例,二进制文件通常采用的是read方法,如下:
std::string str;
ifstream file;
file.open("test.txt");
if(file.is_open())
{
//一行行读
while(getline(file,str))
{
cout<<str<<std::endl;
}
file.close();
}
4 文件的位置
ifstream 与istream一样,有获取流开始读取的位置的接口。
ofstream与ostream一样,有获取流开始写入的位置的接口。
fstream 同时有获取读与写位置接口,与iostream一样。
tellg() == get position 获取当前流的读取位置
tellp() == put position 获取当前流的写入位置。
seekg ( position ); seekg ( offset, direction ); 改变读取位置
seekp ( position ); seekp ( offset, direction ); 改变写入位置。
ios::beg | offset counted from the beginning of the stream |
ios::cur | offset counted from the current position |
ios::end | offset counted from the end of the stream |
如何获取二进制文件的大小,如:
file.open("test.bin",ios::binary|ios::ate);
int size=file.tellg(); //通过标志ate得到文件大小。
file.seekg(0,ios::beg); //把读取位置重新写入文件开头。