[英]Problem with reading a binary file in cpp?
我有一個名為“input.bin”的二進制文件,其中每個字符都是 4 位。 該文件包含此類數據:
0f00 0004 0018 0000 a040 420f 0016 030b
0000 8000 0000 0000 0000 0004 0018 0000
其中 0f 是第一個字節。
我想讀取這些數據並這樣做,我使用以下代碼:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
char buffer[100];
std::ifstream myFile ("input.bin", std::ios::in | std::ios::binary);
myFile.read (buffer, 100);
if (!myFile.read (buffer, 100)) {
std::cout << "Could not open the required file\n";
}
else
{
for (int i = 0; i < 4; i++)
{
std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << std::endl;
}
myFile.close();
}
return 0;
}
目前我只打印四個字節的數據,當我運行它時,我得到這個 output:
buffer[0] = 0
buffer[1] = 24
buffer[2] = 0
buffer[3] = 0
為什么它不打印 0f 的值,而只在索引 1 中打印 18 的值,而實際上它在索引 6 處?
問題就在這里
myFile.read (buffer, 100);
if (!myFile.read (buffer, 100)) {
你讀了兩次,因此忽略了前 100 個字節(如果它們超過 100 個)。
刪除第一個read
,或將條件更改為if (!myFile)
您將數據的內容打印為字符。 前四個字節都不是真正可打印的字符。
您需要將它們打印為(無符號)整數:
// Unsigned bytes to avoid possible sign extensions in conversions
unsigned char buffer[100];
...
// Convert the bytes to unsigned int for printing their numerical values
std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << '\n';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.