C++ 标准流,文件流
- ■ 标准输入,输出流,
- ■ 文件流(ofstream写入,ifstream读取,fstream创建-写入-读取)
- ■ open()
- ■ ofstream
- ■ ifstream
- ■ 流插入<<
- ■ 文件位置指针
■ 标准输入,输出流,
iostream 标准库,它提供了 cin 和 cout 方法
■ 文件流(ofstream写入,ifstream读取,fstream创建-写入-读取)
1. C++ 源代码文件中包含头文件 <iostream> 和 <fstream>。
2.
数据类型 | 描述 |
---|---|
ofstream | 该数据类型表示输出文件流,用于创建文件并向文件写入信息。 |
ifstream | 该数据类型表示输入文件流,用于从文件读取信息。 |
fstream | 该数据类型通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。 |
■ open()
void open(const char *filename, ios::openmode mode);
模式标志 | 描述 |
---|---|
ios::app | 追加模式。所有写入都追加到文件末尾。 |
ios::ate | 文件打开后定位到文件末尾。 |
ios::in | 打开文件用于读取。 |
ios::out | 打开文件用于写入。 |
ios::trunc | 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。 |
■ ofstream
以写入模式打开文件,并希望截断文件,以防文件已存在
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
■ ifstream
打开一个文件用于读写
ifstream afile;
afile.open("file.dat", ios::out | ios::in );
■ 流插入<<
流插入运算符( << )向文件写入信息
ifstream afile;
afile.open("file.dat", ios::out | ios::in );
示例一:
#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: "; 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;
}
当上面的代码被编译和执行时,它会产生下列输入和输出:$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
■ 文件位置指针
istream 和 ostream 都提供了用于重新定位文件位置指针的成员函数。
这些成员函数包括关于
istream 的 seekg(“seek get”)
ostream 的 seekp(“seek put”)
seekg 和 seekp 的参数通常是一个长整型。
// 定位到 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 );