阅读量:133
在C++中,read() 函数通常用于从文件或其他输入流中读取数据
以下是一个使用 std::ifstream 和异常处理的示例:
#include
#include
#include
int main() {
std::ifstream file("example.txt");
if (!file) {
std::cerr << "Error opening file."<< std class="hljs-keyword">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 class="hljs-built_in">what()<< std class="hljs-keyword">return 1;
} catch (...) {
std::cerr << "Unknown exception caught while reading the file."<< std class="hljs-keyword">return 1;
}
file.close();
return 0;
}
在这个示例中,我们首先检查文件是否成功打开。如果打开失败,我们将输出错误消息并返回非零值。然后,我们使用 try 块来读取文件的每一行。如果在读取过程中发生 I/O 错误,我们将捕获 std::ios_base::failure 异常并输出相应的错误消息。如果捕获到其他类型的异常,我们将输出一个通用的错误消息。最后,我们关闭文件并返回 0。