在C++中,read()
函數(shù)通常用于從文件或其他輸入流中讀取數(shù)據(jù)
以下是一個(gè)使用 std::ifstream
和異常處理的示例:
#include<iostream>
#include <fstream>
#include<string>
int main() {
std::ifstream file("example.txt");
if (!file) {
std::cerr << "Error opening file."<< std::endl;
return 1;
}
std::string line;
try {
while (std::getline(file, line)) {
// Process the line
}
} catch (const std::ios_base::failure& e) {
std::cerr << "I/O error: " << e.what()<< std::endl;
return 1;
} catch (...) {
std::cerr << "Unknown exception caught while reading the file."<< std::endl;
return 1;
}
file.close();
return 0;
}
在這個(gè)示例中,我們首先檢查文件是否成功打開。如果打開失敗,我們將輸出錯(cuò)誤消息并返回非零值。然后,我們使用 try
塊來讀取文件的每一行。如果在讀取過程中發(fā)生 I/O 錯(cuò)誤,我們將捕獲 std::ios_base::failure
異常并輸出相應(yīng)的錯(cuò)誤消息。如果捕獲到其他類型的異常,我們將輸出一個(gè)通用的錯(cuò)誤消息。最后,我們關(guān)閉文件并返回 0。