在二进制文件中查找特定的原语

Finding specific primitives within a binary file

本文关键字:原语 查找 二进制文件      更新时间:2023-10-16

是否有任何方法可以在二进制文件中找到特定的原语(例如MATLAB中的read或Mathematica中的BinaryReadLists)?具体来说,我想扫描我的文件,直到它达到,说一个int8_t精度数,然后将其存储在一个变量中,然后扫描另一个原语(unsigned char, double等)?

我正在从MATLAB重写代码,这样做,所以文件的格式是已知的。

我想在文件中读取指定类型(32位int, char,…)的n个字节。例如:如果文件返回8位整数

,则只读取文件的前12个字节

也许你的问题的解决办法是理解这两个文档页面的区别:

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
}