Sun Studio 12 Update 1:C++ 用户指南

14.4.1 使用类 fstream 处理文件

处理文件类似于处理标准输入和标准输出;类 ifstreamofstreamfstream 分别从类 istreamostreamiostream 派生而来。作为派生的类,它们继承了插入和提取运算符(以及其他成员函数),还有与文件一起使用的成员和构造函数。

可将文件 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);

该代码:

14.4.1.1 打开模式

该模式由枚举类型 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);

14.4.1.2 在未指定文件的情况下声明 fstream

可以在未指定文件的情况下声明 fstream,并在以后打开该文件。例如,以下代码创建了 ofstream toFile,以便进行写入。


ofstream toFile;
toFile.open(argv[1], ios::out);

14.4.1.3 打开和关闭文件

可以关闭 fstream,然后使用另一文件打开它。例如,要在命令行上处理提供的文件列表:


ifstream infile;
for (char** f = &argv[1]; *f; ++f) {
   infile.open(*f, ios::in);
   ...;
   infile.close();
}

14.4.1.4 使用文件描述符打开文件

如果了解文件描述符(如整数 1 表示标准输出),可以使用如下代码打开它:


ofstream outfile;
outfile.attach(1);

如果通过向 fstream 构造函数之一提供文件名或使用 open 函数来打开文件,则在销毁 fstream(通过 delete 销毁或其超出作用域)时,会自动关闭该文件。将文件 attachfstream 时,不会自动关闭该文件。

14.4.1.5 在文件内重新定位

您可以在文件中改变读取和写入的位置。有多个工具可以达到这个目的。


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 值。