C++文件输入和输出(C++学习笔记 1)

为了打开一个文件供输入或输出,头文件需要包括

#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>
#include<fstream>
#include<string>
using namespace std;

int main()
{
        ofstream outfile("out_file.txt"); //声明一个ofstream类型的对象,为了打开一个输出文件
        ifstream infile("in_file.txt"); //声明一个ofstream类型的对象,为了打开一个文件供输入
        if(!infile) //如文件不能打开值为false
        {
                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)
                outfile << word << ' ';
        return 0;
}

猜你喜欢

转载自blog.csdn.net/aaqian1/article/details/83472752