c++ - 从 matlab 中的二进制文件读取 float 不正确

标签 c++ arrays matlab floating-point binaryfiles

我试图在 matlab 中读取存储在二进制文件中的 float 组。最初文件是通过内存映射技巧用 C++ 代码创建的。

C++代码:

#include <iostream>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() 
{
    const char* filePath   = "test_file.dat";
    const size_t NUM_ELEMS = 11;

    /* Write the float array to the binary file via memory mapping */
    const size_t NUM_BYTES = NUM_ELEMS * sizeof(float);//array of the 11 floats;    
    int fd = open(filePath, O_RDWR | O_CREAT | O_TRUNC, 0);//open file
    lseek (fd, NUM_BYTES - 1, SEEK_SET);//stretch the file size
    write(fd, "", 1);//write empty string at the end of file
    float* mappedArray = (float*)mmap(0, NUM_BYTES, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);//map array to the file

    for(size_t i = 0; i < NUM_ELEMS; ++i)//fill array
        mappedArray[i] = static_cast<float>(i) / 10.0f;

    munmap(mappedArray, NUM_BYTES);
    close(fd);

    /* Test reading the recorded file*/    
    std::ifstream fl(filePath, std::ios::in | std::ios::binary);
    float data = 0.0f;
    for(size_t i = 0; i < NUM_ELEMS; ++i)
    {
        fl.read(reinterpret_cast<char*>(&data), sizeof(data)); 
        std::cout<<data<<"\n";
    }

    fl.close();
}

从 C++ 代码测试文件读取显示正确结果 - 文件已成功记录。 C++读取结果:

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8

但是,尝试从 matlab 读取此文件会产生错误(数据不正确):

Matlab代码:

function out = readDataFromFile()
    fid = fopen('test_file.dat','r','b'); 
    out = fread(fid, 11, '*float');  
    fclose(fid);
end

matlab读取结果:

0 -429492128 -428443584 -6,3526893e-23 -429492160 8,8281803e-44 -6,3320104e-23 4,1723293e-08 -428443616 2,7200760e+23 4,6006030e-41

我想指出,如果我编写 uint8_t(或 unsigned char)数组,从 matlab 读取此文件会成功。 我在 matlab 中做错了什么?

我的系统 - 64 位 Ubuntu 13.04,c++ 编译器 - gcc 4.8,ma​​tlab - 2013a

最佳答案

问题通过替换解决

fid = fopen('test_file.dat','r','b');

fid = fopen('test_file.dat','r');

关于c++ - 从 matlab 中的二进制文件读取 float 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233919/

相关文章:

matlab - 从输入输出数据估计传递函数

matlab - 如何在 Matlab 绘图中插入两个 X 轴

C++ 为什么在处理类时应该使用 get 和 set 函数

c++ - 如何设置在 Windows 登录屏幕上打开应用程序的按钮

c++ - STL 和 Hana 元组之间的转换

c# - 你能帮我理解这个 C# 函数吗?

arrays - i18next 渲染 JSON 数组

c - 提取数组中的唯一元素(来自 K 和 R C ex1-14)

c++ - 面向 MATLAB 用户的调试编译语言简介

c++ - 具有强加原型(prototype) C++ 的大小方法