16 views (last 30 days)
Hi so im trying to use fread in a very simple program. Ive used the following to write 4 numbers into a .txt file:
fprintf(fid,'%0.0f %0.0f %0.0f %0.0f', 2, 4, 6, 8);
Now i want to read the data back in by reopening the file and reading into an array:
now if i output 'numbers' i get some completely random numbers:
[ 50 32 52 32 54 32 56]
What am i doing wrong? I should be getting [2 4 6 8] back?
Also if anyone knows why im getting an output 'ans=0' that would be useful too.
Jan on 4 Apr 2012
fprintf writes the data as ASCII strings, so you get the string "2 4 6 8" in the file. The binary representation of this string is:
Str = '2 4 6 8';
>> 50 32 52 32 54 32 56
E.g. char(32) is the space character.
Strings written by fprintf are read by fscanf:
fid = fopen('data.txt');
numbers = fscanf(fid, '%f %f %f %f);
fread is thought for reading data written by fwrite.
See also the help and doc for these 4 commands.