0

我需要从文件中准确读取 32 位。我在 STL 中使用 ifstream。我能不能直接说:

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/

4

2 回答 2

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.

请注意,这样做会引入对您的代码的平台依赖性,因为整数中的字节顺序在不同的平台上是不同的。

于 2010-09-02T22:19:12.847 回答
2

int32typedef对于您平台上的 32 位有符号整数类型,将是一个。该基础类型肯定会operator>>为它重载。

更新

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

于 2010-09-02T22:12:39.673 回答