fwrite to fread changes data completely!

8 ビュー (過去 30 日間)
hello_world
hello_world 2016 年 7 月 9 日
編集済み: per isakson 2016 年 7 月 9 日
Hello Friends,
I have a Vector or some length, say, 1 x N with real number entries.
I want to save this vector by using "fwrite" and then read it using "fread". I did the following:
fileID = fopen(Name, 'w');
fwrite(fileID, Vector, 'double', [number_of_rows number_of_columns]);
%Here [number_of rows number_of_cols] = size(Vector);
fclose(fileID);
In workspace, Vector shows of type 'double'
Next, for reading it, I did the following:
fid = fopen(path_to_vector, 'r');
output = fread(fid, [1 length_of_vector], 'double');
fclose(fid);
However, the "output" shows completely different values than what I saved using "fwrite". I tried to change precision from double to type float, int, etc., but it does not work. How can I get exactly the same vector what I saved?
I will appreciate any advise!
  2 件のコメント
per isakson
per isakson 2016 年 7 月 9 日
Are you writing and reading on the same system?
hello_world
hello_world 2016 年 7 月 9 日
Yes.

サインインしてコメントする。

採用された回答

per isakson
per isakson 2016 年 7 月 9 日
編集済み: per isakson 2016 年 7 月 9 日
This works for me on R2016a,Win7,64b. (Replacing real*8 by double doesn't change that.)
>> cssm( rand(1,1000) )
ans =
1
where
function ok = cssm( vec )
fid = fopen( 'cssm.bin', 'w' );
fwrite( fid, vec, 'real*8' );
fclose( fid );
fid = fopen( 'cssm.bin', 'r' );
out = fread( fid, size(vec), 'real*8' );
fclose( fid );
ok = all(vec==out);
end
  2 件のコメント
hello_world
hello_world 2016 年 7 月 9 日
Thanks you for reply!
I tried it before your answer and it worked for me too. The only difference in my previous code and this response is that while writing "fwrite", you do not use vector size. I do not know how does it make a difference.
per isakson
per isakson 2016 年 7 月 9 日
編集済み: per isakson 2016 年 7 月 9 日
vector size &nbspis not a documented input argument of fwrite. See fwrite, Write data to binary file. IMO: fwrite ought to have issued at least a warning.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by