# OOP - I/O Streams ## :books: 介紹 --- 在C++裡面有一個能夠讀取、寫入外部文件的功能,它儲存在一個叫做fstream的函式庫,其中比較常用的函式是 * ifstream: input file stream * ofstream: output file stream ## :books: Code Segments --- 透過以下的範例就可以了解它們如何使用它們囉~~ - ### Example: 在文字檔內寫上字串 ```cpp #include <iostream> #include <fstream> // 這兩行可以讓你不用在每次使用相關函數時,還要在前面打 std:: using namespace std; using std::ofstream; int main() { cout << "Opening... " << endl; // 使用output file的功能,並將它宣告為fout // 用法就如一般的cout ofstream fout; //此處須注意 test.txt的路徑,否則可能會讀不到檔案 fout.open("test.txt", ios::app); fout << "i want a hippo for christmas\n" << "i rlly need that cool thing"; fout.close(); cout << "Appendation is done! " << endl; return 0; } ``` 執行完後可以發現要寫入的文件已經出現上述兩句話了! * ### Example: 輸入數字並儲存於文件中 ```cpp #include <iostream> #include <fstream> #include <cstdlib> // for the function exit // exit(0) 代表成功執行,exit(1) 則表示執行失敗 using std::ifstream; using std::ofstream; using std::cout; using std::cin; using std::endl; int main() { ofstream output; output.open("test.txt", std::ios::app); // 測試是否有打開文件 if (output.fail() ) { cout << "Fail to input..." << endl; exit(1); } int a, b, c; cin >> a >> b >> c; output << "The sum of the input\n" << "is " << (a + b + c) << endl; output.close(); return 0; } ``` 執行完後可以發現你輸入的數字的加總已經出現在文件中了! ###### tags: `C++=>OOP`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up