在二进制文件中查找特定的原语
Finding specific primitives within a binary file
是否有任何方法可以在二进制文件中找到特定的原语(例如MATLAB中的read或Mathematica中的BinaryReadLists)?具体来说,我想扫描我的文件,直到它达到,说一个int8_t精度数,然后将其存储在一个变量中,然后扫描另一个原语(unsigned char, double等)?
我正在从MATLAB重写代码,这样做,所以文件的格式是已知的。
我想在文件中读取指定类型(32位int, char,…)的n个字节。例如:如果文件返回8位整数
也许你的问题的解决办法是理解这两个文档页面的区别:
http://www.mathworks.com/help/matlab/ref/fread.htmlhttp://www.cplusplus.com/reference/cstdio/fread/
两个版本的fread都允许您从二进制文件中拉入项目数组。从你的问题中我假设你知道你需要的数组的大小和形状。
#include <stdio.h>
int main() {
const size_t NumElements = 128; // hopefully you know
int8_t myElements[NumElements];
FILE *fp = fopen("mydata.bin", "rb");
assert(fp != NULL);
size_t countRead = fread(myElements, sizeof(int8_t), NumElements, fp);
assert(countRead = NumElements);
// do something with myElements
}
你的问题对我来说没有意义,但这里有一堆关于如何读取二进制文件的随机信息:
struct myobject { //so you have your data
char weight;
double value;
};
//for primitives in a binary format you simply read it in
std::istream& operator>>(std::istream& in, myobject& data) {
return in >> data.weight >> data.value;
//we don't really care about failures here
}
//if you don't know the length, that's harder
std::istream& operator>>(std::istream& in, std::vector<myobject>& data) {
int size;
in >> size; //read the length
data.clear();
for(int i=0; i<size; ++i) { //then read that many myobject instances
myobject obj;
if (in >> obj)
data.push_back(obj);
else //if the stream fails, stop
break;
}
return in;
}
int main() {
std::ifstream myfile("input.txt", std::ios_base::binary); //open a file
std::vector<myobject> array;
if (myfile >> array) //read the data!
//well that was easy
else
std::cerr << "error reading from file";
return 0;
};
此外,如果您碰巧知道在哪里可以找到您要查找的数据,您可以使用ifstream
的.seek(position)
成员直接跳到文件中的特定点。
哦,你只是想读取文件的前12个字节作为8位整数,然后接下来的12个字节作为int32_t?
int main() {
std::ifstream myfile("input.txt", std::ios_base::binary); //open a file
std::vector<int8_t> data1(12); //array of 12 int8_t
for(int i=0; i<12; ++i) //for each int
myfile >> data1[i]; //read it in
if (!myfile) return 1; //make sure the read succeeded
std::vector<int32_t> data2(3); //array of 3 int32_t
for(int i=0; i<3; ++i) //for each int
myfile >> data2[i]; //read it in
if (!myfile) return 1; //make sure the read succeeded
//processing
}
相关文章:
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- 出于什么目的,可能需要从Boost库中同步原语和容器
- 使用 c++11 的并发原语是否有一个体面的wait_any实现?
- 如何使用编译时常量原语的类型
- 从 JNI 中的原语获取数字的简单方法
- 如何在 Windows 上仅使用事件和联锁原语实现递归锁
- 库在C/C++和其他语言中重现Java原语hashCode逻辑
- 提升::精神(经典)原语与自定义解析器
- 如何从更基本的同步原语中创建多读/单写锁
- boost::asio:"strand"类型的同步原语有什么名称吗?
- Qt同步原语可以与非QThread线程一起使用吗
- std::vector<> 使用 resize() 派生,它不初始化原语和转发construct_back
- 数据结构的线程安全性,在哪里添加同步原语
- 我可以将哪些同步原语与克隆(2)(C/C++)一起使用
- 在使用jni时,如何清理jfloat等原语?
- 使用cgal创建参数化的3D原语
- 按值传递原语
- 将我转换的.obj文件转换为OpenGL原语
- 在SFML顶点数组中组合原语
- 在二进制文件中查找特定的原语