当前位置: 代码迷 >> 综合 >> 使用fstream文件输入和输出
  详细解决方案

使用fstream文件输入和输出

热度:94   发布时间:2024-01-16 03:18:55.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!"。