目錄
一、文件 IO 的基本概念
二、文件流的基本操作
1. 打開文件
2. 關閉文件
3. 檢查文件是否成功打開
三、文本文件的讀寫操作
1. 寫入文本文件(ofstream)
2. 讀取文本文件(ifstream)
四、二進制文件的讀寫操作
1. 寫入二進制文件
2. 讀取二進制文件
五、文件打開模式
六、異常處理與文件 IO
七、常見錯誤與調試技巧
八、完整示例
1. 文本文件的讀寫
2. 二進制文件的讀寫
九、總結
C++從入門到入土學習導航_c++學習進程-CSDN博客
一、文件 IO 的基本概念
C++ 中的文件 IO(輸入/輸出)操作主要通過 ifstream
(輸入文件流)和 ofstream
(輸出文件流)實現,它們分別用于從文件讀取數據和向文件寫入數據。
ifstream
:從文件讀取數據(輸入流)。ofstream
:向文件寫入數據(輸出流)。fstream
:支持同時讀取和寫入文件(雙向流)。
頭文件:#include <fstream>
繼承關系:ifstream
繼承自 istream
,ofstream
繼承自 ostream
,fstream
繼承自 iostream
。
二、文件流的基本操作
1. 打開文件
可以通過以下兩種方式打開文件:
- 構造函數直接打開:
std::ifstream ifs("example.txt"); // 以只讀模式打開文件 std::ofstream ofs("output.txt"); // 以寫入模式打開文件
- 使用?
open()
?方法:std::ifstream ifs; ifs.open("example.txt"); // 以默認模式打開文件
2. 關閉文件
文件操作完成后需調用 close()
方法釋放資源:
ifs.close(); // 關閉輸入流
ofs.close(); // 關閉輸出流
3. 檢查文件是否成功打開
使用 is_open()
方法檢查文件是否成功打開:
if (!ifs.is_open()) {std::cerr << "文件打開失敗!" << std::endl;
}
三、文本文件的讀寫操作
1. 寫入文本文件(ofstream)
使用 <<
插入器向文件寫入數據:
#include <fstream>
#include <iostream>int main() {std::ofstream ofs("output.txt");if (!ofs) {std::cerr << "無法創建文件!" << std::endl;return 1;}ofs << "Hello, World!" << std::endl;ofs << "This is a test." << std::endl;ofs.close();return 0;
}
2. 讀取文本文件(ifstream)
使用 >>
提取器或 getline()
逐行讀取數據:
#include <fstream>
#include <iostream>
#include <string>int main() {std::ifstream ifs("output.txt");if (!ifs) {std::cerr << "文件不存在!" << std::endl;return 1;}std::string line;while (std::getline(ifs, line)) {std::cout << line << std::endl;}ifs.close();return 0;
}
四、二進制文件的讀寫操作
1. 寫入二進制文件
使用 write()
方法以二進制格式寫入數據:
#include <fstream>
#include <iostream>struct Data {int id;double value;
};int main() {Data data = {1, 3.14};std::ofstream ofs("binary.dat", std::ios::binary); // 以二進制模式打開if (!ofs) {std::cerr << "無法創建二進制文件!" << std::endl;return 1;}ofs.write(reinterpret_cast<char*>(&data), sizeof(data)); // 寫入結構體ofs.close();return 0;
}
2. 讀取二進制文件
使用 read()
方法以二進制格式讀取數據:
#include <fstream>
#include <iostream>struct Data {int id;double value;
};int main() {Data data;std::ifstream ifs("binary.dat", std::ios::binary); // 以二進制模式打開if (!ifs) {std::cerr << "無法讀取二進制文件!" << std::endl;return 1;}ifs.read(reinterpret_cast<char*>(&data), sizeof(data)); // 讀取結構體ifs.close();std::cout << "ID: " << data.id << ", Value: " << data.value << std::endl;return 0;
}
五、文件打開模式
模式 | 描述 |
---|---|
std::ios::in | 以讀取模式打開文件(默認用于?ifstream )。 |
std::ios::out | 以寫入模式打開文件(默認用于?ofstream )。 |
std::ios::app | 追加模式,在文件末尾寫入內容。 |
std::ios::binary | 以二進制模式打開文件(默認是文本模式)。 |
std::ios::trunc | 如果文件存在,則清空內容(默認用于?ofstream )。 |
std::ios::ate | 打開文件后立即將文件指針定位到文件末尾。 |
組合模式示例:
std::ofstream ofs("log.txt", std::ios::out | std::ios::app); // 追加寫入
六、異常處理與文件 IO
文件操作可能因文件不存在、權限不足等原因失敗,需結合異常處理:
#include <fstream>
#include <iostream>
#include <stdexcept>int main() {try {std::ifstream ifs("missing.txt");if (!ifs) {throw std::runtime_error("文件打開失敗!");}// 讀取文件...} catch (const std::exception& e) {std::cerr << "異常: " << e.what() << std::endl;}return 0;
}
七、常見錯誤與調試技巧
-
文件路徑問題
- 相對路徑:相對于當前工作目錄(通常為項目根目錄)。
- 絕對路徑:如?
"C:/Users/YourName/Desktop/file.txt"
。 - 解決方法:檢查文件是否存在,或使用?
std::filesystem::absolute()
?獲取絕對路徑(C++17 起)。
-
文件權限問題
- 確保程序有權限讀取/寫入目標文件(如修改文件屬性或運行程序時以管理員權限啟動)。
-
二進制文件讀寫不一致
- 二進制寫入和讀取必須使用相同的模式(如?
std::ios::binary
),否則可能導致數據損壞。
- 二進制寫入和讀取必須使用相同的模式(如?
-
調試工具
- 使用?
std::cerr
?輸出錯誤信息。 - 使用?
Valgrind
?檢測內存泄漏。 - 使用?
GDB
?或 IDE 調試器逐步執行代碼。
- 使用?
八、完整示例
1. 文本文件的讀寫
#include <fstream>
#include <iostream>
#include <string>int main() {// 寫入文件std::ofstream ofs("example.txt");if (ofs) {ofs << "C++ 文件 IO 示例" << std::endl;ofs << "這是第二行內容。" << std::endl;ofs.close();}// 讀取文件std::ifstream ifs("example.txt");if (ifs) {std::string line;while (std::getline(ifs, line)) {std::cout << line << std::endl;}ifs.close();}return 0;
}
2. 二進制文件的讀寫
#include <fstream>
#include <iostream>struct Student {int id;std::string name;
};int main() {Student student = {101, "Alice"};std::ofstream ofs("students.dat", std::ios::binary);if (ofs) {ofs.write(reinterpret_cast<char*>(&student), sizeof(Student));ofs.close();}Student readStudent;std::ifstream ifs("students.dat", std::ios::binary);if (ifs) {ifs.read(reinterpret_cast<char*>(&readStudent), sizeof(Student));ifs.close();std::cout << "ID: " << readStudent.id << ", Name: " << readStudent.name << std::endl;}return 0;
}
九、總結
通過 ifstream
和 ofstream
,可以高效地實現 C++ 中的文件讀寫操作。關鍵點包括:
- 正確使用文件模式(如?
std::ios::binary
、std::ios::app
)。 - 檢查文件是否成功打開(
is_open()
)。 - 結合異常處理(
try/catch
)確保程序健壯性。 - 區分文本和二進制文件的讀寫方式。
- 調試文件路徑和權限問題,避免因環境問題導致失敗。