处理文件类似于处理标准输入和标准输出;类 ifstream、ofstream 和 fstream 分别从类 istream、ostream 和 iostream 派生而来。作为派生的类,它们继承了插入和提取运算符(以及其他成员函数),还有与文件一起使用的成员和构造函数。
可将文件 fstream.h 包括进来以使用任何 fstream。如果只要执行输入,请使用 ifstream;如果只要执行输出,请使用 ofstream;如果要对流执行输入和输出,请使用 fstream。将文件名称用作构造函数参数。
例如,将文件 thisFile 复制到文件 thatFile,如以下示例所示:
ifstream fromFile("thisFile"); if (!fromFile) error("unable to open ’thisFile’ for input"); ofstream toFile ("thatFile"); if (!toFile) error("unable to open ’thatFile’ for output"); char c; while (toFile && fromFile.get(c)) toFile.put(c); |
该代码:
使用 ios::in 的缺省模式创建名为 fromFile 的 ifstream 对象,并将其连接到 thisFile。然后打开 thisFile。
检查新的 ifstream 对象的错误状态,如果它处于失败状态,则调用 error 函数(必须在程序中其他地方定义)。
使用 ios::out 的缺省模式创建名为 toFile 的 ofstream 对象,并将其连接到 thatFile。
按上文所述检查 toFile 的错误状态。
创建 char 变量用于存放传递的数据。
将 fromFile 的内容复制到 toFile,每次一个字符。
当然这种方法(每次复制一个字符)不适用于复制文件。该代码只是 fstream 使用示例。应该将与输入流关联的 streambuf 插入输出流中。请参见14.10 streambuf和手册页 sbufpub(3CC4)。
该模式由枚举类型 open_mode 中的 or-ing 位构造,它是类 ios 的公有类型,其定义如下:
enum open_mode {binary=0, in=1, out=2, ate=4, app=8, trunc=0x10, nocreate=0x20, noreplace=0x40}; |
UNIX 中不需要 binary 标志,提供该标志是为了与需要它的系统兼容。可移植代码在打开二进制文件时要使用 binary 标志。
您可以打开文件同时用于输入和输出。例如,以下代码打开了文件 someName 用于输入和输出,同时将其连接到 fstream 变量 inoutFile。
fstream inoutFile("someName", ios::in|ios::out); |
可以在未指定文件的情况下声明 fstream,并在以后打开该文件。例如,以下代码创建了 ofstream toFile,以便进行写入。
ofstream toFile; toFile.open(argv[1], ios::out); |
可以关闭 fstream,然后使用另一文件打开它。例如,要在命令行上处理提供的文件列表:
ifstream infile; for (char** f = &argv[1]; *f; ++f) { infile.open(*f, ios::in); ...; infile.close(); } |
如果了解文件描述符(如整数 1 表示标准输出),可以使用如下代码打开它:
ofstream outfile; outfile.attach(1); |
如果通过向 fstream 构造函数之一提供文件名或使用 open 函数来打开文件,则在销毁 fstream (通过 delete 销毁或其超出作用域)时,会自动关闭该文件。将文件 attach 到 fstream 时,不会自动关闭该文件。
您可以在文件中改变读取和写入的位置。有多个工具可以达到这个目的。
tellg (tellp) 是报告文件位置的 istream (ostream) 成员函数。因为 istream 和 ostream 是 fstream 的父类,所以 tellg 和 tellp 还可以作为 fstream 类的成员函数调用。
seekg (seekp) 是查找给定位置的 istream (ostream) 成员函数。
seek_dir enum 指定相对位置以用于 seek。
enum seek_dir {beg=0, cur=1, end=2}; |
例如,给定 fstream aFile:
streampos original = aFile.tellp(); //save current position aFile.seekp(0, ios::end); //reposition to end of file aFile << x; //write a value to file aFile.seekp(original); //return to original position |
seekg (seekp) 可以采用一个或两个参数。如果有两个参数,第一个参数是相对于 seek_dir 值(也就是第二个参数)指示的位置的位置。例如:
aFile.seekp(-10, ios::end); |
从终点移动 10 个字节
aFile.seekp(10, ios::cur); |
从当前位置向前移 10 个字节。
并不能方便地在文本流中进行任意查找,但总是可以返回到以前保存的 streampos 值。