【筆記】C++ 檔案讀寫 iofstream

簡述

檔案讀寫的用途以小作品來說是常常會用到的,像是遊戲的歷史紀錄、模擬貼文等等,想用 txt 檔存資料的時候都很常使用。

使用檔案讀寫功能請先引入 <fstream> 標頭檔。

ofstream 表示要輸出到某文件的類別,而不是要輸出到程式。
ifstream 同理,只是這是輸入到程式中,而不是輸入到檔案。

檔案寫入

main.cpp
1
2
3
4
5
6
7
ofstream ofs;  // Output File Stream
ofs.open("test.txt"); // Open the file u want to write in
if (ofs.fail()) { // Debug, if file opening failed;
cout << "File opening failed\n";
// ...
}
ofs << "Hi! World";
test.txt
1
Hi! World

那如果在執行一次程式呢?

test.txt
1
Hi! World

結果還是一樣。如果我們要添加內容,而不是覆蓋內容,可以將 ofs.open("test.txt"); 改成 ofs.open("test.txt", ios::app); 這個 app 推測是 append 也就是附加、添加內容。所以我們將下方的程式碼執行 2 次,原本 txt 檔裡的內容就不會被覆蓋。

main.cpp
1
2
3
4
5
6
7
ofstream ofs;  // Output File Stream
ofs.open("test.txt", ios::app); // Open the file u want to write in
if (ofs.fail()) { // Debug, if file opening failed;
cout << "File opening failed\n";
// ...
}
ofs << "Hi! World";
test.txt
1
Hi! WorldHi! World

檔案讀取

使用方式與檔案寫入相似。

text.txt
1
Hi! World
main.cpp
1
2
3
4
5
6
7
8
9
ifstream ifs;  // Input File stream
ifs.open("text.txt"); // Open the file u want to read
if (ifs.fail()) { // Debug, if file opening failed;
cout << "File opening failed\n";
// ...
}
string str;
ifs >> str;
cout << str << '\n';
Output Result
1
Hi!

為什麼只有 Hi! 呢?其實就跟 cin 一樣,遇到空白就是為輸入完了,所以只擷取到 Hi! 的部分,那要一直重複寫 ifs >> str; 這行?不用,可以用 EoF 的方式做讀取。

main.cpp
1
2
3
4
5
6
7
8
9
10
ifstream ifs;  // Input File stream
ifs.open("text.txt"); // Open the file u want to read
if (ifs.fail()) { // Debug, if file opening failed;
cout << "File opening failed\n";
// ...
}
string str;
while (ifs >> str) {
cout << str << '\n';
}
Output Result
1
2
Hi!
World

或是用 getline() 直接讀取整行,忽略空白字元

main.cpp
1
2
3
4
5
6
7
8
9
10
ifstream ifs;  // Input File stream
ifs.open("text.txt"); // Open the file u want to read
if (ifs.fail()) { // Debug, if file opening failed;
cout << "File opening failed\n";
// ...
}
string str;
while (getline(ifs, str)) {
cout << str << '\n';
}
Output Result
1
Hi! World

資料型態一定要用字串存取嗎?不用,看你的檔案放什麼,你就可以用什麼存,整數就用 int,小數點就用 float,都是可以的。

參考資料

  • C++ 檔案讀寫函式庫 fstream - 上