[英]Read 4 bytes a time with ifstream from binary file
I have a binary file that contains floats so that every 4 bytes are a float.我有一个包含浮点数的二进制文件,因此每 4 个字节都是一个浮点数。 I'm not sure how I can read in a way that every four bytes would be stored as a float so I can do whatever I need with it.
我不确定如何以每四个字节存储为浮点数的方式进行读取,这样我就可以用它做任何我需要的事情。
Here's my code:这是我的代码:
int main()
{
float i;
std::ifstream inFile("bin_file", std::ios::binary);
while (inFile >> i)
{
std::cout << i;
}
inFile.close();
return 0;
}
In that case, it won't even enter the while loop unless I define i as a char.在这种情况下,除非我将 i 定义为字符,否则它甚至不会进入 while 循环。 I guess that's because it reads 1 byte every time and can't store it as a float.
我猜那是因为它每次读取 1 个字节并且不能将其存储为浮点数。 Btw I've checked and the file opens.
顺便说一句,我已经检查过了,文件打开了。
Thanks!谢谢!
The operator>>
in streams is designed for formatted data (ie strings).流中的
operator>>
专为格式化数据(即字符串)而设计。 You want to use read
instead:您想改用
read
:
int main()
{
float i;
std::ifstream inFile("bin_file", std::ios::binary);
while(inFile.read(reinterpret_cast<char*>(&i), sizeof(i))) {
std::cout << i;
}
inFile.close();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.