'fwrite' does not write 'char' variables in binary files

8 ビュー (過去 30 日間)
blenis22
blenis22 2019 年 3 月 18 日
編集済み: blenis22 2019 年 3 月 24 日
I am reading a binary phase space file (* .egsphsp #), for simulations monteCarlo with EGSnrc.
My problem is in the file header. The floating variables read them in 1 byte with fread, however, the characters are read in 2 bytes, which causes problems when I generate my own phase space file, since fwrite writes the characters in 1 byte and as double.
Part of my codes:
READ
fprintf ('Reading phase space file ... \ n')
MODE_RW = setstr (fread (fid, 5, 'uchar')) '; % Mode
NPPHSP = fread (fid, 1, 'int32'); %
NPHOTPHSP = fread (fid, 1, 'int32'); %
EKMAXPHSP = fread (fid, 1, 'float32'); %
EKMINPHSP = fread (fid, 1, 'float32'); %
NINCPPHSP = fread (fid, 1, 'float32'); %
Header_File = struct ('Mode', MODE_RW, 'total_particles', ... NPPHSP,' total_photons', NPHOTPHSP, Max_energy ', ... EKMAXPHSP,' Min_energy ', EKMINPHSP, ...' particles_source ', NINCPPHSP);
WRITE
MODE_RW = Header_File.Mode;
NPPHSP = Header_File.total_particles;
NPHOTPHSP = Header_File.total_photons;
EKMAXPHSP = Header_File.Max_energy;
EKMINPHSP = Header_File.Min_energy;
NINCPPHSP = Header_File.particles_source;
fid_w = fopen ('prueba.egsphsp1', 'wb');
g = 1;
if g == 0% zlast
a = fwrite (fid_w ,MODE_RW, 'uchar');
b = fwrite (fid_w, NPPHSP, 'int32');
c = fwrite (fid_w, NPHOTPHSP, 'int32');
d = fwrite (fid_w, EKMAXPHSP, 'float32');
e = fwrite (fid_w, EKMINPHSP, 'float32');
f = fwrite (fid_w, NINCPPHSP, 'float32');
.
.
.
'a' and 'MODE_RW' are not of the same class and have different bytes.
I need to read five characters in 5 bytes (1 byte / char). How do I do it?

採用された回答

Titus Edelhofer
Titus Edelhofer 2019 年 3 月 18 日
Hi,
I'm not really sure if this is not working as it should. If you do the following:
fid = fopen('foo.bin', 'wb');
fwrite(fid, 'hello', 'uchar');
fclose(fid)
you will have a file created with 5 bytes. The return argument of fwrite may be double, but it only tells you that you wrote 5 bytes, not the content.
Now for the reading: if you want to have 5 bytes (and not 5 characters with 2 bytes each) do the following:
fid = fopen('foo.bin', 'rb');
s = fread(fid, '*uchar')';
str = char(s) % you indeed read the hello from above
whos s % will have uint8, i.e., the ascii code
fclose(fid);
Titus
  1 件のコメント
blenis22
blenis22 2019 年 3 月 19 日
編集済み: blenis22 2019 年 3 月 24 日
Dear Titus,
Thank you very much for your contribution (the first option). I had an error in my code, now it works.
Thank you
Greetings, Bladimir

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

その他の回答 (1 件)

blenis22
blenis22 2019 年 3 月 19 日
Hi,
I need the variable that reads the first five bytes to be of the same class and size in bytes as the variable that is written to the file

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by