【问题标题】:Reading uint8_t from binary file从二进制文件中读取 uint8_t
【发布时间】:2018-08-24 08:36:54
【问题描述】:

我有一个包含二进制数的文件,我必须阅读它们。我用:

ifstream data("date.txt", ios_base::binary);

int count_16 = 0; //count how many uint16_s I have already read
uint16_t numbers_16; // Allocate storage for uint16_s
int count_8 = 0;
uint8_t numbers_8;
int count_char = 0;
char name[20];

data.seekg(0U, ios_base::beg); // Move the input position indicator to the beginning of the file for reading
data.read(reinterpret_cast<char*>(&numbers_16), sizeof(uint16_t)); // into numbers_16
cout << numbers_16; 
count_16++;

data.seekg(count_16 * sizeof(uint16_t) + count_8 * sizeof(uint8_t) + count_char * sizeof(name+1));
data.read(reinterpret_cast<char*>(&numbers_16), sizeof(numbers_16)); // Read the element into number
cout << numbers_16 << endl;
count_16++;

在此之前一切正常:

data.seekg(count_16 * sizeof(uint16_t) + count_8 * sizeof(uint8_t) + count_char * sizeof(name+1));
data.read(reinterpret_cast<char*>(&numbers_8), sizeof(numbers_8)); // Read the element into number
cout << numbers_8 << endl;
count_8++;

在这里我没有得到任何数字或任何可读的东西。 我不知道为什么这种方法适用于 uint16_t 但不适用于 uint8_t。有人可以解释为什么它是错误的以及如何从文件中读取 uint8_t 吗?

【问题讨论】:

  • 你能发布你的data.txt文件吗
  • 数字是原始格式还是文本?通常“.txt”扩展名表示 ASCII 文本,即 '1' 的 0x31 而不是 0x01。
  • 顺便说一句,您不需要在打开文件后查找文件的开头(除非您以附加模式打开它);文件会自动设置到开头。
  • 根据您的代码,count_8 为零,因此表达式count_8 * sizeof(uint8_t) 也为零。我了解您为什么要重新定位文件指针。通过读取结构或数据块,您的程序可能会更有效,而不是寻找下一个uint16_t
  • 顺便说一句,count_char 也为零。因此,您只寻求count_16 * sizeof(uint16_t)。使用调试器。

标签: c++ file binary


【解决方案1】:

事实证明,阅读是件好事。唯一的错误在这里:

cout << numbers_8 << endl;

我刚刚在 numbers_8 之前写了 (int),现在看起来很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 2011-03-14
    相关资源
    最近更新 更多