最近,需要驗證c與matlab進行的同一個下變頻,下采樣操作結果是否一致,於是,需要將c處理後的數據存儲下來,在matlab讀取,發現自己對c讀取文件的操作並不是很熟悉,於是,對此,進行一番總結。
在vs裏面隨機生成100個float數據,然後存爲dat文件,最後在matlab端進行讀取;
vs
#include<iostream>
#include<ctime>
#include<string>
using namespace std;
int main()
{
//生成隨機float
srand((float)time(0));
float *num = new float[100];
for (int i = 0; i < 100; i++)
num[i] =((float) rand())/10000;
for (int i = 0; i < 100; i++)
{
if (i % 10 == 0)
cout << endl;
cout << num[i] << " ";
}
//存儲
FILE *f_float = NULL;
errno_t err;
string filename = "D:/visualStudio/FILE_storedat/" + to_string((int)1000) + ".dat";
err = fopen_s(&f_float, filename.c_str(), "wb");
if (err != 0) {
printf(" Open failed\n");
return 1;
}
else
printf(" Open success\n");
fwrite(num,sizeof(float),100, f_float);
fclose(f_float);
return 0;
}
matlab
clc;clear;close;
fid=fopen('1000.dat','rb');
data=fread(fid,'float')
fclose(fid);
可以看出,結果一樣;
瞭解到,c++可以通過fstream來讀取文件,以後再來進行補充