C++ 入門指南 4.01
練習 23.4 參考程式 - 練習檔案處理
// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// 引入標準程式庫中相關的檔案處理程式
#include <fstream>
// cout 為 std 中的輸出物件
using std::cout;
// endl 為 std 中的斷行符號
using std::endl;
// string 為 std 中的字串型態
using std::string;
// cout 為 std 中的錯誤輸出物件
using std::cerr;
// fstream 為 std 中的檔案處理類別
using std::fstream;
int main(void) {
// 預計寫入字串
string text("There is no spoon.\n");
// 預計寫入檔名
string filename("spoon.txt");
// 宣告檔案物件
fstream textfile;
// 以指定檔名開啟檔案
textfile.open(filename, std::ios_base::app);
// 先檢查檔案是否開啟
if (!textfile.is_open()) {
// 顯示開啟失敗的訊息
cerr << "寫入失敗" << filename << endl;
} else {
// 開啟成功進行寫入
textfile.write(text.data(), text.size());
// 顯示寫入成功的訊息
cerr << "寫入成功" << endl;
// 關閉檔案物件
textfile.close();
}
// 最後回傳 0 給作業系統
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise2304.cxx
編譯:g++ exercise2304.cxx
執行:./a.out
功能:C++入門指南單元二十三的練習
作者:張凱慶 */
回到練習題目