What's the most basic way to format a 2D matrix of doubles in binary for reading into IDL?

删除回忆录丶 提交于 2019-12-11 06:49:22

问题


So I have an i by j matrix of doubles in C++ that I want to read into an IDL program.

Lets say that the matrix is called data, with size ROWS by COLS, and name string saved to filename. And I just write the values out in a stream to a binary file.

ofstream myfile (filename, ios::binary);
if(myfile.isopen())
{
  for (int i = 0; i < ROWS; i++){
     for (int j=0; j < COLS; j++){
          myfile<<data.at(i,j);
}
myfile.close();

I then want to read it back into IDL but I'm new to working with binary in IDL and following the documentation has gotten me here but it's not working.

function read_binmatrix, filename, ROWS, COLS, thetype

    mat = READ_BINARY(filename,DATA_TYPE=thetype,DATA_DIMS=[ROWS-1,COLS-1])
    return, mat

end
 ...
 ...
matrix = read_binmatrix(file2,num_rows,num_cols,5)

...but I get this error as output.

% READ_BINARY: READU: End of file encountered. Unit: 100, File:
...
% Execution halted at: READ_BINMATRIX     21 
...

回答1:


 myfile<<data.at(i,j); 

writes text to the file, not binary data. To write the numbers in binary format use std::ofstream::write():

 myfile.write(reinterpret_cast<char*>(&data.at(i,j),sizeof(decltype(data.at(i,j)))); 


来源:https://stackoverflow.com/questions/38577060/whats-the-most-basic-way-to-format-a-2d-matrix-of-doubles-in-binary-for-reading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!