2010-09-02 72 views
0

我需要从文件中读取完整的32位。我在STL中使用ifstream。我能不能直接说:我需要定义“>>”运算符来使用cin用Int32的吗?

int32 my_int; 
std::ifstream my_stream; 

my_stream.open("my_file.txt",std::ifstream::in); 
if (my_stream && !my_stream.eof()) 
    my_stream >> my_int; 

......或者我需要以某种方式覆盖>>运算符INT32工作?我没有看到INT32这里列出: http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/

回答

3

流提取操作符(>>)执行格式化 IO,而不是二进制IO。您需要改用std::istream::read。您还需要打开文件binary。哦,并且检查std::istream::eof在您的代码中是多余的。

int32 my_int; 
std::ifstream my_stream; 

my_stream.open("my_file.txt",std::ios::in | std::ios::binary); 
if (my_stream) 
{ 
    my_stream.read(reinterpret_cast<char*>(&my_int), sizeof(my_int)); 
} 
//Be sure to check my_stream to see if the read succeeded. 

注意,这样做是要在你的代码引进平台的依赖,因为字节的整数的顺序是在不同平台上的不同。

+0

是的,但不是很大的endian几乎死亡或死亡?我还没有看到年龄的solaris系统... – 2010-09-02 22:43:15

+0

@Jason:ARM不会死亡或死亡:)此外,大多数文件格式和网络协议被指定为大端(由于某种原因)。 – 2010-09-03 00:06:59

+0

哦,忘了ARM是大端endian。卫生署!好东西,我的代码不会在任何智能手机上使用; o) – 2010-09-03 20:13:32

2

int32将是任何类型恰好是你的平台上的32位有符号整数typedef。该底层类型肯定会为其重载operator>>

更新

正如下面比利指出的,流被设计用于读取文本,并将其解析为过载的数据类型。因此,在您的代码示例中,它将查找一系列数字字符。因此,它不会从您的文件中读取32位。

+1

但是,这不会从文件中读取完整的32位。 – 2010-09-02 22:15:08

+0

@比利:好点,我会更新我的答案... – 2010-09-02 22:19:04

+0

+1为编辑。 – 2010-09-02 22:21:22