3 回答
TA貢獻1828條經驗 獲得超3個贊
每個失敗的系統調用都會更新該errno值。
因此,您可以ifstream通過使用類似以下內容的信息來進一步了解打開失敗時發生的情況:
cerr << "Error: " << strerror(errno);
但是,由于每個系統調用都會更新全局errno值,因此如果另一個系統調用在的執行f.open和使用之間觸發了錯誤,則在多線程應用程序中可能會出現問題errno。
在具有POSIX標準的系統上:
errno是線程本地的;在一個線程中設置它不會影響在其他任何線程中的值。
編輯(感謝Arne Mertz和其他人的評論):
e.what() 起初似乎是一種更符合C ++習慣的正確方法,但是此函數返回的字符串取決于實現,并且(至少在G ++的libstdc ++中)此字符串沒有有關錯誤原因的有用信息...
TA貢獻1850條經驗 獲得超11個贊
您可以嘗試讓流在失敗時引發異常:
std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try {
f.open(fileName);
}
catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
e.what(),但是似乎并沒有太大幫助:
我在Embarcadero RAD Studio 2010 Win7上嘗試過,它給出“ ios_base :: failbit set”,而strerror(errno)給出“沒有這樣的文件或目錄”。
在Ubuntu 13.04上,gcc 4.7.3異常顯示為“ basic_ios :: clear”(感謝arne)
如果e.what()對您不起作用(由于該錯誤未標準化,我不知道會告訴您什么錯誤),請嘗試使用std::make_error_condition(僅C ++ 11):
catch (std::ios_base::failure& e) {
if ( e.code() == std::make_error_condition(std::io_errc::stream) )
std::cerr << "Stream error!\n";
else
std::cerr << "Unknown failure opening file.\n";
}
- 3 回答
- 0 關注
- 3936 瀏覽
添加回答
舉報
