0

バイナリ ファイル (MATLAB の fread や Mathematica の BinaryReadLists など) 内で特定のプリミティブを見つける方法はありますか? 具体的には、ファイルが int8_t 精度数に到達するまでスキャンし、それを変数に格納してから、別のプリミティブ (unsigned char、double など) をスキャンしますか?

これを行う MATLAB のコードを書き直しているので、ファイルの形式はわかっています。

ファイル内の指定された型 (32 ビット int、char、..) のみの n バイトを読み取りたい。例: ファイルが 8 ビット整数に戻った場合、ファイルの最初の 12 バイトのみを読み取る

4

2 に答える 2

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)メンバーを使用して、ファイル内の特定のポイントに直接スキップすることもできます。ifstream

ファイルの最初の 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
}
于 2013-03-28T22:10:45.337 に答える
0

問題の解決策は、次の 2 つのドキュメント ページの違いを理解することかもしれません。

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
}
于 2013-03-28T22:12:31.673 に答える