如何将bin文件每次读取32字节存放到一个vector容器里面,然后每次读取push_back
时间: 2024-11-24 15:43:01 浏览: 39
在C++中,如果你想要逐字节地读取一个`.bin`文件,并将其内容存储到`std::vector<char>`中,每次读取32字节并添加到向量的末尾,可以按照下面的方式来做:
```cpp
#include <fstream>
#include <vector>
void readBinFileIntoVector(const std::string& filename, std::vector<char>& data) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Failed to open the file.");
}
char buffer[32];
while (file.read(buffer, sizeof(buffer))) { // 读取32字节
data.push_back(buffer[0]); // 将每个字节追加到vector的尾部
for (size_t i = 1; i < sizeof(buffer); ++i) {
data.push_back(buffer[i]);
}
}
// 处理文件可能未满32字节的情况
if (file.gcount() > 0) {
file.read(buffer, file.gcount()); // 读取剩余的字节数
for (size_t i = 0; i < file.gcount(); ++i) {
data.push_back(buffer[i]);
}
}
file.close();
}
int main() {
std::vector<char> data;
try {
readBinFileIntoVector("my_file.bin", data);
// 现在data vector包含了整个文件的内容,按32字节的块读取
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
这个`readBinFileIntoVector`函数会打开文件,循环读取直到文件结束,每次读取32字节,然后将这些字节逐个压入`data`向量。注意最后部分用于处理文件长度不是32字节整数倍时的边界情况。
阅读全文
相关推荐

















