为了打开一个文件供输入或输出,头文件需要包括
#include<iostream> 和#include<fstream>
iostream库除了支持终端输入输出,也支持文件的输入和输出。
1. 打开一个输出文件
必须声明一个ofstream类型的对象,来打开一个输出文件:
ofstream outfile( “name-of-the-file” );
测试是否已经成功地打开了文件:
if( ! outfile ) //文件不能打开,则值为false
cerr << “Unable to open the file!\n”;
2.打开一个文件供输入
必须声明一个ifstream类型的对象:
ifstream infile( “name-of-the-file” );
测试是否已经成功地打开了文件:
if( ! infile )
cerr << “Unable to open the file!\n”;
3.(例)编写一个简单程序
#include<iostream>