添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Oracle Solaris Studio 12.2:C++ 用户指南

13.4.1 使用类 fstream 处理文件

处理文件类似于处理标准输入和标准输出;类 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

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 构造函数之一提供文件名或使用 open 函数来打开文件,则在销毁 fstream (通过 delete 销毁或其超出作用域)时,会自动关闭该文件。将文件 attach fstream 时,不会自动关闭该文件。

13.4.1.5 在文件内重新定位

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

streampos 是可以记录 iostream 中的位置的类型。

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 值(也就是第二个参数)指示的位置的位置。例如: