首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 文件操作入門:fstream 讀寫數據完整示例

     編輯:關於C++

頭文件與流對象

  • #include <fstream>
  • 輸出文件流:ofstream(寫),模式 ios::out。
  • 輸入文件流:ifstream(讀),模式 ios::in。
  • 雙向:fstream,模式 ios::in | ios::out。

寫入文件

ofstream outfile("data.txt", ios::out);
if (!outfile) { cerr << "open error!"; exit(1); }
for (int i = 0; i < 10; ++i) {
    int x; cin >> x;
    outfile << x << '\n'; // 像用 cout 一樣
}
outfile.close(); // 可選,析構時自動關閉

讀取文件

ifstream infile("data.txt", ios::in);
if (!infile) { cerr << "open error!"; exit(1); }
int x, maxv = -1e9;
while (infile >> x) { // 類似 cin,遇 EOF 為 false
    if (x > maxv) maxv = x;
}
infile.close();
cout << "Max: " << maxv << '\n';

關鍵點

  • 流對象(outfile/infile)用於操作,而非文件名字符串。
  • ios::out 會截斷文件(清空),追加用 ios::app。
  • 二進制模式:ios::binary,配合 read()/write()。
  • 隨機訪問:seekg()/seekp(),tellg()/tellp()。
  • 錯誤狀態:fail(), bad(), eof(), good()。

完整示例:寫入結構體數組(二進制)

struct Student { int id; char name[20]; double score; };
Student stu[3] = {{1,"Alice",92.5},{2,"Bob",87.0},{3,"Carol",95.5}};
// 寫二進制
ofstream ofs("stu.dat", ios::out | ios::binary);
ofs.write(reinterpret_cast(stu), sizeof(stu));
ofs.close();
// 讀二進制
Student read_stu[3];
ifstream ifs("stu.dat", ios::in | ios::binary);
ifs.read(reinterpret_cast(read_stu), sizeof(read_stu));
ifs.close();

總結

  • C++ 文件流以 iostream 風格操作,類型安全、可擴展。
  • 文本模式適合人類可讀數據,二進制模式適合高效存儲結構體/數組。
  • 總是檢查打開是否成功,善用 RAII(析構自動關閉)。

這是 C++ 文件 I/O 的基礎模板,掌握後可處理絕大多數數據持久化需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved