Put float data into mat-file using fwrite function

5 views (last 30 days)
I am writing a program in C, its job is: get datas from txt file and put them into a mat file. I use fwrite function to write the data, codes as below:
fwrite(&data, typesize, 1750, pf);
but it doesn't always works, when the data type is float, it may cause the mat file load failure.
??? Error using ==> load
Unable to read MAT-file
D:\out.mat
File may be corrupt.
e.g.
if it writes 1750 datas like 1.005312, the file corrupt.
if it writes 1750 datas like 0.369306 or 1699300.000000, it works very well.
Is the type float in C the same to Single in matlab? or How to fix it?
Kindly help!

Accepted Answer

R Zh
R Zh on 20 Aug 2012
Solved, the mat-file should be a binary file, codes as bellow,
pf = fopen( OutFileName, "wb+");
Thanks all the same.
  2 Comments
Walter Roberson
Walter Roberson on 20 Aug 2012
Jan, notice that double-quotes were used in the wb+ string. That gives us the clue that the line is C or C++ code, not MATLAB code.
Also, .mat files can be accessed with fwrite() . It is more often a nuisance to do so for variables that were compressed in place, but compression is optional and variables that are not compressed are in binary format suitable for fwrite()
Jan
Jan on 20 Aug 2012
@Walter: I obviously misunderstood the intention of the OP. Of course MAT file can be written using FWRITE, because this command can create every file, which can be created. But this is neither secure nor comfortable. I've deleted my comment which unfortunately reduces the power of your reply. Sorry.

Sign in to comment.

More Answers (1)

José-Luis
José-Luis on 17 Aug 2012
If you really want to create a mat file from scratch, then you should read the white paper first:
It is not really straigthforward, I think you are better off using the Matlab C++ API:
Cheers!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!