2014-02-26 20 views
1

這裏是XXD的TEST.bin,燒寫將二進制文件讀入犰狳矩陣的直接方法是什麼?

0000000: 0100 0200 0300 0400 0500 0600 0700 0800 ................ 
0000010: 0900 0a00 0200 0400 0600 0800 0a00 0c00 ................ 
0000020: 0e00 1000 1200 1400 0300 0600 0900 0c00 ................ 
0000030: 0f00 1200 1500 1800 1b00 1e00   ............ 

結果這只不過是短整型的序列,每個大小爲2個字節。

我現在想到的是創建一個arma::Mat<short>,然後在文件中讀入兩個字節,然後將這兩個字節按位切換轉換爲short int,然後將其分配到Mat中。

這應該有效,但看起來乏味,有沒有更好的方法?

回答

1

與TonyWilk提示,我想出了以下內容:

#include <sys/stat.h> 
#include <stdint.h> 
#include <armadillo> 

int main() 
{ 
    struct stat statbuf; 
    stat("bigmat.bin", &statbuf); 
    uintmax_t fsize = (uintmax_t)statbuf.st_size; 
    uintmax_t bsize = fsize/sizeof(short); 
    short buffer[bsize]; 
    FILE *fp = fopen("bigmat.bin", "rb"); 
    fread((void*) buffer, 1, fsize, fp); 
// for(uintmax_t i=0; i<bsize; i++) { 
//  printf("%hd \n", buffer[i]); 
// } 

    arma::Mat<short> mymat(buffer, 10, 3, false); 
    std::cout << mymat << std::endl; 
    return 0; 
} 
1

您可以將整個文件讀入短數組。是這樣的:

#define BUF_SIZE 12345; 
short int buffer[BUF_SIZE]; 

FILE *fp= fopen("test.bin", "rb"); 
int nread= fread((void *)buffer, 1, BUF_SIZE, fp); 

既然我猜你正在使用C++,你可以判斷文件大小前閱讀並動態地創建緩衝區。你仍然需要單獨轉換小/大端。