漫步云端

移动开发(Android、iPhone、Windows Mobile) | JAVA | C | C++ | .net | Objective C | 微软企业开发技术 | 嵌入式系统设计与开发
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++ iostream和fstream的示例

Posted on 2010-12-08 23:05  charley_yang  阅读(2278)  评论(0编辑  收藏  举报
      从一个名为 in_file.txt 的文本文件中读取单词,然后把每个词写到一个名为out_file.txt的输出文件中 并且每个词之间用空格分开
/*********************************************************
* Description:iostream 与 fstream 类
* Author:charley
* DateTime:2010-12-8 22:00
* Compile Environment:win7+vs2008
***********************************************************/

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std;
 
int main_test3() 
{ 
    //声明一个 ofstream类型的对象
    ofstream outfile( "out_file.txt" ); 
    //声明一个 ifstream类型的对象
    ifstream infile( "in_file.txt" ); 

    // 如文件不能打开值为 false 
    if ( ! infile ) { 
        cerr << "error: unable to open input file!\n"; 
        return -1; 
    } 
    if ( ! outfile ) { 
        cerr << "error: unable to open output file!\n"; 
        return -2; 
    } 
    string word; 
    while ( infile >> word )    //从infile文件读取内容,类似等待用户的控制台出入
        outfile << word << ' '; //向内容文件outfile写入,类似往控制台输出内容
  
 return 0; 
}