iostream库支持 文件的输入和输出。为了打开一个文件提供输入和输出,除了iostream头文件外,还需要包含:#include <fstream>
下面是一个简单的程序。它从一个名为in_file的文本文件中读取单词,然后把每个单词写到一个名为out_file的输出文件中,并且每个词之间用空格分开。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream outfile("out_file.txt");
ifstream infile("in_file.txt");
if (!infile)
{cerr<<"error:unable to open input file!\n";
return -1;}
if(!outfile)
{cerr<<"error:unalbe to open output file!\n";
return -2;}
string word;
while (infile>>word)
outfile<<word<<' ';
return 0;
}
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream outfile("out_file.txt");
ifstream infile("in_file.txt");
if (!infile)
{cerr<<"error:unable to open input file!\n";
return -1;}
if(!outfile)
{cerr<<"error:unalbe to open output file!\n";
return -2;}
string word;
while (infile>>word)
outfile<<word<<' ';
return 0;
}
如是,新建一个in_file.txt,内容是“This is my file”,则目录下出现out_file.txt