【问题标题】:What's the C++ equivalent of this matlab code (fread matlab vs fread C/C++)?这个 matlab 代码的 C++ 等价物是什么(fread matlab vs fread C/C++)?
【发布时间】:2018-11-20 13:40:08
【问题描述】:

正在尝试转换此 matlab 代码:

fid = fopen([fpath, '/file.bin'],'rb');
content = fread(fid, 11,'single');

我目前的尝试如下:

FILE* f = fopen(filename.c_str(),"rb");
char *content = (char*) malloc (sizeof(float)*11);
size_t result;
result = fread(content,4,11,f);

这对我来说很有意义,但它不起作用。

更新

文件的第一行应该是这样的:

120.0 120.0 120.0 -1.0 -1.0 -1.0 0.05000000074505806 0.25 2.0 2.0 2.0

我还检查了f 指针是NULL,但它不是。当我打开文件并加载内容,然后打印它时,它什么也不显示。

【问题讨论】:

  • “不起作用”是什么意思?你想要 C 还是 C++?你的代码看起来像带有一点 C++ 的 C
  • 标题说 C++,代码说 C(好吧,它可能编译为 C++,但实际上主要是 C),标签说两者。
  • @Biffen filename.c_str() 我不会打赌,但那可能是std::string
  • 你检查过FILE指针f不是NULL吗?

标签: c++ c file


【解决方案1】:

您可能想要使用输入流。

例如读一行

std::ifstream f(filename);
std::array<float, 11> content;
std::copy_n(std::istream_iterator<float>(f), 11, content.begin());

或多个

std::ifstream f(filename);
std::vector<std::array<float, 11>> content;
for (std::string line; std::getline(f, line);) {
    std::stringstream ss(line);
    std::array<float, 11> datum;
    std::copy_n(std::istream_iterator<float>(f), 11, datum.begin());
    content.push_back(datum);
}

【讨论】:

  • 我不明白为什么我得到的都是零。 0 0 0 0 0 0 0 0 0 0 0
  • 如果您在循环中添加std::cout &lt;&lt; line &lt;&lt; std::endl;,您会在输出中看到文件中的行吗?
猜你喜欢
  • 2011-01-09
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多