ios ios istream ostream ifstream ofstream include fstream

  • Slides: 15
Download presentation

ios 類別 ios istream ostream ifstream ofstream 可用來建立檔案物件,進行檔案處理。 需載入 #include <fstream> 標頭檔

ios 類別 ios istream ostream ifstream ofstream 可用來建立檔案物件,進行檔案處理。 需載入 #include <fstream> 標頭檔

檔案的開啟範例 ifstream inf; inf. open(“d: \test. txt”, ios: : in); 檢查檔案是否開啟成功 ifstream inf(“d: \test.

檔案的開啟範例 ifstream inf; inf. open(“d: \test. txt”, ios: : in); 檢查檔案是否開啟成功 ifstream inf(“d: \test. txt”, ios: : in); if( inf. is_open() ) {…… } else {…… } 檔案的關閉範例 inf. close();

//從檔案讀取資料 int main() { char txt[80]; ifstream ifile(“d: \donkey. txt”, ios: : in); if(

//從檔案讀取資料 int main() { char txt[80]; ifstream ifile(“d: \donkey. txt”, ios: : in); if( ifile. is_open() ) while( !ifile. eof() ) //判別是否讀到檔案的尾端 { ifile >> txt; //將檔案內容寫入字元陣列 cout << txt << endl; } else cout << “檔案開啟失敗…” << endl; ifile. close(); return 0; } //關閉檔案

//利用 put() 將字串寫入檔案 int main() { char txt[]=“Welcome to the C++ world”; int i=0;

//利用 put() 將字串寫入檔案 int main() { char txt[]=“Welcome to the C++ world”; int i=0; ofstream ofile(“d: \welcome. txt”, ios: : out); if( ofile. is_open() ) { while( txt[i] != ‘’ ) ofile. put(txt[i++]); cout << “字串寫入完成…” << endl; } else cout << “檔案開啟失敗…” << endl; ofile. close(); //關閉檔案 return 0; }

//文字檔的拷貝與讀取 int main() { char txt[80], ch; ifstream ifile 1(“d: \welcome. txt”, ios: :

//文字檔的拷貝與讀取 int main() { char txt[80], ch; ifstream ifile 1(“d: \welcome. txt”, ios: : in); ofstream ofile(“d: \welcome 2. txt”, ios: : out); while( ifile 1. get(ch) ) ofile. put(ch); cout << “拷貝完成…” << endl; ifile 1. close(); ofile. close(); ifstream ifile 2(“d: \welcome 2. txt”, ios: : in); while( !ifile 2. eof() ) { ifile 2. getline(txt, 80, ’n’); cout << txt << endl; } ifile 2. close(); return 0; }