2013-07-13 46 views
2

我正在嘗試使用下面的代碼從文件中讀取數據。 (請注意,您需要啓用GCC C++ 11層的功能,使這個編譯)std :: basic_ifstream引發std :: bad_cast

#include <fstream> 

typedef unsigned char byte; 

int main() 
{ 
    std::string filename = "test.cpp"; 
    std::basic_ifstream<byte> in(filename, std::basic_ifstream<byte>::in | std::basic_ifstream<byte>::binary); 
    in.exceptions(std::ios::failbit | std::ios::badbit); 
    byte buf[5]; 
    in.read(buf, 5); 
    return 0; 
} 

然而,在讀取數據時我得到一個異常:

terminate called after throwing an instance of 'std::bad_cast' 
    what(): std::bad_cast

這種情況發生在in.read(buf, 5)命令被調用。

我知道我可以通過不設置我設置的異常掩碼來抑制此異常,但這不能解決問題,它只能掩蓋它。如果沒有例外掩碼,代碼將繼續工作,但讀取0個字符。

有誰知道爲什麼拋出這個異常?我該如何讓它消失?

+0

對我來說更多細節,它甚至不編譯:'沒有匹配的構造函數的「的std :: basic_ifstream ' – 2013-07-13 08:00:09

+2

@ H2CO3正如介紹中陳述初始化,您需要啓用C + +11。否則,'basic_ifstream'的構造函數不存在。另一種修正:使用'filename.c_str()'而不是'filename'。 – Chris

+1

此問題已在此解決:http://stackoverflow.com/q/19205531/331024它具有char_traits的完整實現和codecvt

回答

2

C++ STL實例只包含char_traits的兩個專業:

struct char_traits <char>; 
    struct char_traits <wchar_t >; 

張貼工作的定義代碼char_traits<byte>是必需的。

this SO question

1

如果您重新定義bytecharbad_cast異常將不再發生 發生。

我推測basic_ifstream模板沒有完全調試爲 unsigned char專業化。根據標準§27.3, char_traits<CharType>只需要通過庫 爲CharType = {char|char16_t|char32_t|wchar_t}

相關問題