在二进制文件中查找特定基元

时间:2013-03-28 21:32:12

标签: c++ file binary primitive-types

有没有办法在二进制文件中找到特定的基元(例如MATLAB中的fread或Mathematica中的BinaryReadLists)?具体来说,我想扫描我的文件,直到它到达,比如一个int8_t精度数,然后将它存储在一个变量中,然后扫描另一个原语(unsigned char,double等等)?

我正在重写MATLAB中执行此操作的代码,因此文件的格式是已知的。

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

2 个答案:

答案 0 :(得分:0)

你的问题对我没有意义,但这里有一堆关于如何读取二进制文件的随机信息:

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;
};

此外,如果您碰巧知道在哪里找到您要查找的数据,则可以使用.seek(position)的{​​{1}}成员直接跳到文件中的特定点。

哦,你只想将文件的前12个字节读取为8位整数,然后接下来的12个字节作为int32_t?

ifstream

答案 1 :(得分:0)

也许您的问题的解决方案是理解这两个文档页面之间的区别:

http://www.mathworks.com/help/matlab/ref/fread.html http://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
}