1. 程式人生 > >C++檔案輸入和輸出

C++檔案輸入和輸出

為了開啟一個檔案供輸入或輸出,標頭檔案需要包括

#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; }