文章

C++ 文件

C++ 文件

C++iostream标准库除了提供从标准输入读取流istream向标准输出写入流ostream,还提供从文件读取流和向文件写入流fstream

要在 C++ 中进行文件处理,必须在 C++ 源代码文件中包含头文件 <iostream><fstream>

数据类型

数据类型描述
ofstream该数据类型表示输出文件流,用于创建文件并向文件写入信息。
ifstream该数据类型表示输入文件流,用于从文件读取信息。
fstream该数据类型通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,
这意味着它可以创建文件,向文件写入信息,从文件读取信息。

打开文件

在从文件读取信息或者向文件写入信息之前,必须先打开文件。

ofstreamfstream 对象都可以用来打开文件进行写操作,如果只需要打开文件进行读操作,则使用 ifstream 对象。

  • open()函数
1
void open(const char *filename, ios::openmode mode);

open()fstreamifstreamofstream对象的一个成员,第一个参数是要打开的文件位置,第二个参数是文件被打开的模式

模式标志描述
ios::app追加模式。所有写入都追加到文件末尾。
ios::ate文件打开后定位到文件末尾。
ios::in打开文件用于读取。
ios::out打开文件用于写入。
ios::trunc如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。

如果想要以写入模式打开文件,并希望截断文件,以防文件已存在,可以使用下述语法:

1
2
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

如果想打开一个文件用于读写,则:

1
2
fstream  afile;
afile.open("file.dat", ios::out | ios::in );

关闭文件

当 C++ 程序终止时,它会自动关闭刷新所有流,释放所有分配的内存,并关闭所有打开的文件。

但是为了防止意外,一般都建议在程序终止前手动关闭文件。

关闭文件用到close()函数,close()fstreamifstreamofstream对象的一个成员。

1
void close();

读取写入文件

在C++中,一般使用流插入运算符<<向文件写入信息,用流提取运算符>>从文件读取信息。操作的对象为fstreamofstreamifstream

程序示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
    
   char data[100];

   // 以写模式打开文件
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 

   // 接受长度不超过100的字符串
   cin.getline(data, 100);

   // 向文件写入用户输入的数据
   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;

   // 把缓冲区里的那个残余的换行符丢掉
   cin.ignore();
   
   // 再次向文件写入用户输入的数据
   outfile << data << endl;

   // 关闭打开的文件
   outfile.close();

   // 以读模式打开文件
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 

   // 按空格或换行来读取内容,第一次读取第一行
   infile >> data; 

   // 在屏幕上写入数据
   cout << data << endl;
   
   // 再次从文件读取数据,并显示它
   infile >> data; 
   cout << data << endl; 

   // 关闭打开的文件
   infile.close();

   return 0;
}

程序输出

1
2
3
4
5
6
7
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

文件位置指针

istreamostream 都提供了用于重新定位文件位置指针的成员函数。这些成员函数包括关于 istreamseekg(”seek get”)和关于 ostreamseekp(”seek put”)。

seekgseekp的第一个参数是长整型,表示偏移量。第二个参数用于指定查找反向,分别由ios::beg(默认,从流的头开始定位),ios::cur(从流的当前位置开始定位),ios::end(从流的末尾开始定位)

1
2
3
4
5
6
7
8
9
10
11
// 定位到 fileObject 的第 n 个字节(假设是 ios::beg)
fileObject.seekg( n );

// 把文件的读指针从 fileObject 当前位置向后移 n 个字节
fileObject.seekg( n, ios::cur );

// 把文件的读指针从 fileObject 末尾往回移 n 个字节
fileObject.seekg( n, ios::end );

// 定位到 fileObject 的末尾
fileObject.seekg( 0, ios::end );
本文由作者按照 CC BY 4.0 进行授权