Matlab,C++存取二进制

1,Matlab存储二进制

load Wall.dat %读取数据,数组名为Wall
fid=fopen('Wall','wb'); %打开一个文件,二进制写入
fwrite(fid,Wall','float32'); %写入,浮点型32位格式写入,数组要转置,因为是按列存储的
fclose(fid); %关闭文件

 

  • 需要存储多个连续文件时,写一个循环就可以了
for ii=1:10 %连续读10个文件,以Patch开头后面跟数字和格式
    eval(['load ','Patch', int2str(ii),'.dat;'])
    eval(['Temp=Patch', int2str(ii),''';']) %读取存入临时Temp数组并且转置。
    fid=fopen(['Patch',int2str(ii)],'wb');
    fwrite(fid,Temp,'float32');
    fclose(fid);
end

2,C++读取二进制

#include <iostream>
#include <fstream>
using namespace std;
struct VECTOR
{
    float x;
    float y;
    float z;
};
void main()
{
    ifstream in("Wall",ios::binary);
    VECTOR A[4];
    for (int i = 0; i < 4; i++)
    {
        in.read((char*)&A[i].x, sizeof(float));
        in.read((char*)&A[i].y, sizeof(float));
        in.read((char*)&A[i].z, sizeof(float));
    }
    for (int i = 0; i < 4; i++)
        cout << i << "  " << A[i].x << "  " << A[i].y << "  " << A[i].z << endl;
}
  • 读取连续的文件
char temp[64];
string ss;
for(int k=0;k<10;k++)
{
    sprintf(temp,"Patch%d",k+1);
    ifstream in(temp,ios::binary);
        for(int j=0;j<n;j++)
        {
        in.read((char*)&KeyP[k][j].x,sizeof(float));
        in.read((char*)&KeyP[k][j].y,sizeof(float));
        in.read((char*)&KeyP[k][j].z,sizeof(float));
        }
}

 

posted @ 2017-06-03 16:44  大蓝鲸  阅读(492)  评论(0编辑  收藏  举报