2
votes

I'm trying to read in the matlab an array of floats, stored in the binary file. Originally file was created in c++ code, via memory mapping trick.

C++ code:

#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();
}

Test reading of the file from C++ code shows correct result - file was recorded successfully. Result of reading from C++:

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8

However, an attempt to read this file from matlab yields an error (incorrect data):

Matlab code:

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

Result of reading from matlab:

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

I would like to note that if I write uint8_t (or unsigned char) array, reading this file from matlab succeeds. What am I doing wrong in matlab?

My system - 64-bit Ubuntu 13.04, c++ compiler - gcc 4.8, matlab - 2013a

1
Glad you solved this yourself. When you get a chance, move your edit to an answer and mark it as the accepted answer. That way, answerers won't waste time on it. - dmm

1 Answers

0
votes

The problem is solved by replacing

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

at

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