处理文件类似于处理标准输入和标准输出;类 ifstream 、 ofstrea m 和 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 ,每次一个字符。
该模式由枚举类型 open_mode 中的 OR-ing 位构造,它是类 ios 的公有类型,其定义如下:
enum open_mode {binary=0, in=1, out=2, ate=4, app=8, trunc=0x10, nocreate=0x20, noreplace=0x40};
您可以打开文件同时用于输入和输出。例如,以下代码打开了文件 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(); 13.4.1.4 使用文件描述符打开文件 如果了解文件描述符(如整数 1 表示标准输出),可以按如下方式将其打开:ofstream outfile; outfile.attach(1);如果通过向 fstream 构造函数之一提供文件名或使用 open 函数来打开文件,则在通过 delete 销毁 fstream 或其超出作用域时,会自动关闭该文件。将文件 attach 到 fstream 时,不会自动关闭该文件。 13.4.1.5 在文件内重新定位 您可以在文件中改变读取和写入的位置。有多个工具可以达到这个目的。
如果了解文件描述符(如整数 1 表示标准输出),可以按如下方式将其打开:
ofstream outfile; outfile.attach(1);
如果通过向 fstream 构造函数之一提供文件名或使用 open 函数来打开文件,则在通过 delete 销毁 fstream 或其超出作用域时,会自动关闭该文件。将文件 attach 到 fstream 时,不会自动关闭该文件。
您可以在文件中改变读取和写入的位置。有多个工具可以达到这个目的。
streampos 是可以记录 iostream 中的位置的类型。
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 个字节。