从二进制文件中读取uint8_t

时间:2018-03-15 13:43:08

标签: c++ file binary

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

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?

1 个答案:

答案 0 :(得分:0)

事实证明,读书的原因很好。唯一的错误在于:

mysql::Conn

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