檔案的輸入和輸出

2021-08-30 01:23:49 字數 1039 閱讀 7385

iostream庫也支援檔案的輸入和輸出。所有能應用在標準輸入和輸出上的操作符,也都可以應用到已經被開啟的輸入或輸出檔案上。為了開啟乙個檔案供輸入和輸出,除了iostream標頭檔案之外,還必須包含標頭檔案:

#include

為了開啟乙個輸出檔案,我們必須宣告乙個ofstream型別的物件:

ofstream outfile("name-of-file");

為了測試是否已經成功地開啟乙個檔案,我們可以寫出這樣的**:

//如檔案不能開啟值為false

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";

下面是乙個簡單的程式。它從乙個名為in_file的文字檔案中讀取單詞,然後把每個單詞寫到乙個out_file的輸出檔案中,並且為每個詞用空格分開。

#include

#include

#include

int main()

ofstream outfile( "out_file" );

ifstream infile( "in_file" );

if ( ! infile ) {

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;

檔案的輸入和輸出

1 fstream型別定義了兩個自己的新操作 open和close。2 檔案流物件的使用 1 ifstream infile ifile.c str ofstream outfile ofile.c str ifile和ofile儲存讀寫的檔名的string物件 2 ifstream infile ...

檔案的輸入和輸出

1.檔案內建函式 open 和file 作為開啟檔案之門 的 鑰匙 內建函式open 以及file 提供了初始化輸入 輸出 i o 操作的通用介面。open 內建函式成功開啟檔案時候回返回乙個物件,否則會引發乙個錯誤。內建函式open 的基本語法是 file object open file nam...

檔案輸入和輸出,

1.訪問檔案並得到流物件 rstream open a.txt encoding utf 8 2.通過流物件進行讀操作 r 代表的是讀 line rstream.readline 讀一行 lines rstream.readlines 讀全部但是會已字串 n的形式 all rstream.read ...