要结构的C++二进制文件
C++ Binary file to struct
我正试图从二进制文件中读取一些数据。
我设置了一个结构,看起来像这样:
struct track{
unsigned long ID;
string title;
};
以及一个存储等值的文件
[00000001][5468652054726163]
[00000002][6F776C6F6F6B6174]
这是我在某种程度上伪代码中的糟糕逻辑
blocksize = 4; // Read 4 bytes at a time
while(!endoffile){
track[i].ID = (blocksize,pos) // get 4 bytes starting at position
track[i].title = blocksize*2,pos+4) // get 8 bytes starting 4 after last position
pos+12; i++;
}
对不起,太糟糕了。就像我说的,我是C++新手。我知道如何使用fstream等,只是在二进制文件中循环字节的逻辑让我完全失望。
您可以这样做:
#include <cstdint>
#include <fstream>
#include <string>
struct track { uint32_t id; char title[8]; };
std::ifstream infile("thefile.bin");
for (;;)
{
track t;
if (!infile.read(reinterpret_cast<char*>(&t.id), 4) ||
!infile.read(t.title, 8) ||
infile.gcount() != 8)
{
// error, die (or perhaps end of file)
}
// now you can use "t", e.g.:
std::string title(t.title, 8); // a sane string object
}
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作