我需要从文件中准确读取 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/
最佳答案
流提取运算符 (>>>
) 执行格式化 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.
请注意,这样做会引入对代码的平台依赖性,因为整数中字节的顺序在不同平台上是不同的。
关于c++ - 我是否需要定义 ">>"运算符才能将 cin 与 Int32 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3631655/