Search code examples
cmatlabfwrite

C fwrite output does not appear correctly in Matlab


I have this simple code:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


int main(int argc, char * argv[]){

    int N = 4;
    int *A =  malloc( N * sizeof( *A ) );


    for ( int i = 0 ; i < N; i++ ) 
        A[ i ] = i;


    FILE * theFile;
    theFile = fopen( "theA", "wb" );
    assert( NULL != theFile );
    fwrite( A , sizeof( int ) , N , theFile );
    fclose( theFile );


    return 0;
}

Now , if I load the file in matlab , it shows :

 0     0     0     0     1     0     0     0     2     0     0     0     3     0     0     0

If I use this code in order to read from file:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


int main(int argc, char * argv[]){

    int N = 4;
    int *A = malloc( N * sizeof( *A ) );


    FILE * theFile;
    theFile = fopen( "theA", "wb" );
    assert( NULL != theFile );
    fread( A , sizeof( int ) , N , theFile );
    fclose( theFile );

     for ( int i = 0 ; i < N; i++ ) 
        printf("\nA = %d",A[ i ] );



    return 0;
}

it shows :

A = 0
A = 0
A = 0
A = 0

Any explanation?

In matlab I am using:

 fid = fopen('theA','rb')
 A = fread(fid);

Solution

  • You need to specify the precision parameter in Matlab, otherwise by default Matlab fread will read byte by byte.

    Default: 'uint8=>double'

    My C is rusty but I guess the class int cast a 32 bits signed integer. You have to tell this information to Matlab otherwise it uses the default interpretation noted above.

    So in Matlab, simply do:

    fid = fopen('theA','rb')
    A = fread(fid , 'int32' );
    fclose(fid) ;
    

    This will result in:

    A =
         0
         1
         2
         3
    

    Which should be your normal output (at least it is what you wrote in the file initially).