필터 지우기
필터 지우기

FREAD() help

조회 수: 5 (최근 30일)
Edward
Edward 2012년 4월 4일
Hi so im trying to use fread in a very simple program. Ive used the following to write 4 numbers into a .txt file:
fid=fopen('data.txt','wt');
fprintf(fid,'%0.0f %0.0f %0.0f %0.0f', 2, 4, 6, 8);
fclose(fid);
Now i want to read the data back in by reopening the file and reading into an array:
fid=fopen('data.txt');
numbers=fread(fid);
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.
Thanks!

채택된 답변

Jan
Jan 2012년 4월 4일
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';
double(Str)
>> 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.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2012년 4월 4일
You have to specify the precision of the numbers you're reading (i.e. double).
You could also look at dlmread and dlmwrite if the whole text file will be numbers.
  댓글 수: 1
Edward
Edward 2012년 4월 4일
I've tried changing it to use fread(fid,4,'double'); but still get the same random numbers

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by