在C++中读取数据

reading data in C++

本文关键字:数据 读取 C++      更新时间:2023-10-16

我有读取二进制数据的matlab代码:

**nfft    = 256; 
navg    = 1024;
nsamps  = navg * nfft;
f_s     = 8e6;
nblocks = floor(10 / (nsamps / f_s));  
for i = 1:nblocks 
    nstart  = 1 + (i - 1) * nsamps;
    fid     = fopen('data.dat');   % binary data and 320 MB
    fseek(fid,4 * nstart,'bof');
    y       = fread(fid,[2,nsamps],'short');
    x       = complex(y(1,:),y(2,:));
end**

它将为我提供长度高达8e6的复杂数据。

我正试图编写C++来执行与matab相同的函数,但我无法获得所有数据,或者它们不是相同的原始数据。

有人能帮助实现理想吗?

这是我正在编写的C++代码。

非常感谢。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <complex>
#include <vector>
#include <stdlib.h>

 struct myfunc{
    char* name;
 };
int main() {
              FILE* r = fopen("data.bin", "rb");
              fread( w, sizeof(int), 30, r);
              fread(&c, sizeof(myfunc),1,r);
              for(int i=0; i < 30; i++){
                  cout<< i << ".  " << w[i] << endl;
              }
return 0;

}

基于注释

我从结构myfunc调用的c,w是向量。因此它们将是:int w[40];myfunc;

fread(&c, sizeof(myfunc),1,r);

将从文件流CCD_ 1向CCD_。这并不是特别有用,因为无论myfunc.name在写入文件时指向什么地址,在读回文件时几乎肯定都是无效的。

解决方案:写入文件时序列化myfunc.name,读取时反序列化。问题中没有足够的信息来建议如何最好地做到这一点。我会存储字符串Pascal样式,并在myfunc.name的长度前加上前缀,以使读回更容易:

int len = strlen(myfunc.name);
fwrite(&len, sizeof(len), 1, outfile); // write length
fwrite(myfunc.name, len, 1, outfile); // write string

并读取

int len;
fread(&len, sizeof(len), 1, infile); // read length
myfunc.name = new char[len+1]; // size string with space for terminator
fwrite(myfunc.name, len, 1, infile); // read string
myfunc.name[len] = ''; // terminate string

请注意,上面的代码完全忽略了endian和错误处理。