使用fstream文件输入和输出

24 篇文章 0 订阅

 

为了打开一个文件供输入或输出,除了iostream头文件外,还必须包含头文件:

 

#include <fstream>

 

 

 

为了打开一个头文件,我们必须声明一个ofstream类型的对象:

 

ofstream outfile( “ name-of-file” );

 

 

 

为了测试是否已经成功地打开了一个文件,我们可以这样写:

 

if ( !outfile )

 

 

       cerr << “Sorry! We were unable to open the file!/n” ;

 

 

 

类似地,为了打开一个文件供输入,我们必须声明一个ifstream类型的对象:

 

ifstream infile ( “name of file “ );

 

 

if ( ! infile )

 

 

       cerr << “Sorry! We were unable to open the file!/n” ;

 

 

 

举例:

 

#include <fstream>

 

 

#include "iostream.h"

 

 

#include <string>

 

 

 

 

using std::string;

 

 

using std::ofstream;

 

 

using std::ifstream;

 

 

 

 

 

 

int main()

 

 

{

 

 

       ofstream outfile( "out_file " );

 

 

       ifstream infile( "in_file " );

 

 

 

 

       if( !outfile ){

 

 

              cerr << "error: unable to open output file!/n" ;

 

 

              return -1;

 

 

       }

 

 

 

 

       if( !infile ){

 

 

              cerr << "error: unable to open input file!/n" ;

 

 

              return -1;

 

 

       }

 

 

 

 

       string word;

 

 

       while ( infile >> word )

 

 

              outfile <<word << ' ';

 

 

 

 

       return 0;

 

 

}

 

 

运行,结果如下:

error: unable to open input file!

 

 

 

 

运行的结果告诉我们必须先建立一个input file, 另一方面也告诉我们声明了ofstream outfile( "out_file " )后,程序会自动建立文件out_file,  然后我们在且只能在源文件所在目录下(由于没有指定文件路径),新建in_file文件(注意:没有后缀)。

可以用记事本打开,并写入“hello world!”。保存,关闭后,再次运行程序,然后我们在源文件所在目录下,看到新建的output file。

使用记事本打开out_file, 文件里已被写入“hello world!"。

 

 

如果使用文本文档输入输出,则我们在声明ofstream, ifstream时,编写如下代码

ofstream outfile( "out_file.txt" );

 

 

ifstream infile( "in_file.txt" );

 

 

 

 

如果我们想改变文档所在的位置,则可以如下编写代码(将文件路径改为C盘根目录)

 

ofstream outfile( "c:/out_file.txt" );

 

 

ifstream infile( "c:/in_file.txt" );

 

 

 

 

 

 

例子二

 

#include <fstream>

 

 

#include "iostream.h"

 

 

#include <string>

 

 

 

 

using std::string;

 

 

using std::ofstream;

 

 

using std::ifstream;

 

 

 

 

 

 

int main()

 

 

{

 

 

       ofstream outfile( "c:/out_file.txt" );

 

 

       ifstream infile( "c:/in_file.txt" );

 

 

 

 

       if( !outfile ){

 

 

              cerr << "error: unable to open output file!/n" ;

 

 

              return -1;

 

 

       }

 

 

 

 

       if( !infile ){

 

 

              cerr << "error: unable to open input file!/n" ;

 

 

              return -1;

 

 

       }

 

 

 

 

       string word;

 

 

       while ( infile >> word )

 

 

              outfile <<word << ' ';

 

 

 

 

       return 0;

 

 

}

 

 

建立文本文件in_file.txt, 并写入“

hello world!”

 

运行程序

 

 

 

 

 

打开out_file.txt

文件里已被写入“hello world!"。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值