C++ファイル入出力(C++学習ノート1)

3861 ワード

入力または出力のためにファイルを開くには、ヘッダファイルに次のものが必要です.
#includeおよび#include iostreamライブラリは、端末の入出力のほか、ファイルの入出力もサポートします.
1.出力ファイルを開く
出力ファイルを開くには、ofstreamタイプのオブジェクトを宣言する必要があります.
ofstream outfile( “name-of-the-file” );
ファイルが正常に開いたかどうかをテストします.
if(!outfile)/ファイルが開かない場合、false cerr<<「Unable to open the file!」;
2.入力用のファイルを開く
ifstreamタイプのオブジェクトを宣言する必要があります.
ifstream infile( “name-of-the-file” );
ファイルが正常に開いたかどうかをテストします.
if( ! infile ) cerr << “Unable to open the file!”;
3.(例)簡単なプログラムを作成する
#include
#include
#include
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!
"
; return -1; } if(!outfile) { cerr << "error:unable to open output file!
"
; return -2; } string word; while(infile >> word) outfile << word << ' '; return 0; }