已经在之前无数的范例中,我们都使用了
iostream
标准库,使用了它的
cin
和
cout
方法从标准输入读取流和向标准输出写入流
接下来这章节我们将学习如何从文件读取流和向文件写入流。
如何从文件读取流和向文件写入流需要用到 C++ 中另一个标准库
fstream
。
fstream
定义了三个新的数据类型:
在从文件读取信息或者向文件写入信息之前,必须先打开文件。
ofstream
和
fstream
对象都可以用来打开文件进行写操作。
如果只需要打开文件进行读操作,则使用
ifstream
对象
open() 函数是 fstream、ifstream 和 ofstream 对象的一个成员函数,用来打开文件
open() 函数的语法格式如下
void open(const char *filename, ios::openmode mode);
filename : 指定要打开的文件的名称和位置
mode : 指定文件打开的模式
文件打开模式有以下几种
可以使用 close() 函数关闭文件。
close() 函数是 fstream、ifstream 和 ofstream 对象的一个成员
在 C++ 程序终止时,它会自动关闭刷新所有流,释放所有分配的内存,并关闭所有打开的文件。
但程序员应该养成一个好习惯,在程序终止前关闭所有打开的文件
close 成员函数语法格式如下
void close();
流提取运算符( << ) 可以向文件写入信息,就像使用该运算符输出信息到标准输出上一样。
唯一不同的是,写入文件使用的是 ofstream 或 fstream 对象,而不是 cout 对象
流提取运算符( >> ) 可以从文件中读取信息,就像使用该运算符从标准输入读取信息一样
唯一不同的是,读取文件使用的是 ifstream 或 fstream 对象,而不是 cin 对象
范例:读取 & 写入
下面的代码以读写模式打开一个文件 demo.txt 并写入用户输入的信息之后。
然后程序再从文件读取信息,并将其输出到屏幕上
* file: main.cpp
* author: 简单教程(www.twle.cn)
#include <fstream>
#include <iostream>
using namespace std;
int main ()
char data[1024];
// 以写模式打开文件
ofstream outfile;
outfile.open("demo.txt");
cout << "Writing to the file" << endl;
cout << "Enter your message: ";
cin.getline(data, 1024);
// 向文件写入用户输入的数据
outfile << "message:" << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// 再次向文件写入用户输入的数据
outfile << "age:" << data << endl;
// 关闭打开的文件
outfile.close();
// 以读模式打开文件
ifstream infile;
infile.open("demo.txt");
cout << "Reading from the file" << endl;
infile >> data;
// 在屏幕上写入数据
cout << data << endl;
// 再次从文件读取数据,并显示它
infile >> data;
cout << data << endl;
// 关闭打开的文件
infile.close();
return 0;
编译运行以上程序,输出结果如下
$ g++ main.cpp && ./a.out
Writing to the file
Enter your message: www.twle.cn
Enter your age: 29
Reading from the file
message:www.twle.cn
age:29
上面的程序中使用了 cin 对象的附加函数,如 getline() 函数从外部读取一行,ignore() 函数会忽略掉之前读语句留下的多余字符。
文件位置指针
istream 类和 ostream 类都提供了用于重新定位文件位置指针的成员函数
这些成员函数是
istream 的 seekg
ostream 的 seekp
seekg 和 seekp 的参数通常是一个长整型 (long int)
第二个参数可以用于指定查找方向。
查找方向可以以下几种:
ios::beg
: 默认的,从流的开头开始定位
ios::cur
从流的当前位置开始定位
文件位置指针是一个整数值,指定了从文件的起始位置到指针所在位置的字节数。
使用 seekg 定位文件位置指针
定位到 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 );