From: kees de Kapper on
Hi All,

I want to write the header at the end of the procedure, because only then I know the exact content of the file. So I came up with this: (simplified but it reflects the core)
==================================================
FileName = 'C:\Test.bin'
fid = fopen(FileName, 'a', 'l');

Header = cast([0,0,0,0], 'uint16'); % a header of 4 uint16's
count = fwrite(fid, Header, 'uint16', 'l');
Data = cast([1,2,3,4,5,6,7,8,9,0], 'uint16'); % just some data
count = fwrite(fid, Data, 'uint16', 'l');

% just a header
Header(1) = 4;
Header(2) = 10;
Header(3) = 1;
frewind(fid); %I expected that this wil bring me to the beginning of the file
count = fwrite(fid, Header, 'uint16', 'l'); % overwrite the empty header

fclose(fid);
==================================================

However, the 'frewind' and then my attempt to overwrite the old header appeared not to work. What am I doing wrong and how can I solve this?

Thanks in advance,

Kees.
From: Walter Roberson on
kees de Kapper wrote:

> I want to write the header at the end of the procedure, because only
> then I know the exact content of the file. So I came up with this:
> (simplified but it reflects the core)
> ==================================================
> FileName = 'C:\Test.bin'
> fid = fopen(FileName, 'a', 'l');
>
> Header = cast([0,0,0,0], 'uint16'); % a header of 4 uint16's
> count = fwrite(fid, Header, 'uint16', 'l');
> Data = cast([1,2,3,4,5,6,7,8,9,0], 'uint16'); % just some data
> count = fwrite(fid, Data, 'uint16', 'l');
> % just a header
> Header(1) = 4;
> Header(2) = 10;
> Header(3) = 1;
> frewind(fid); %I expected that this wil bring me to the beginning of the
> file

It will.

> count = fwrite(fid, Header, 'uint16', 'l'); % overwrite the empty header

Because you opened with 'a' access type, all writes are defined to take
place at the end of file, so internally before doing this fwrite() the
operating system will move to end of file and add the data after that.

To repair this problem, use an access type of 'w+' if the file is
expected to not already exist or you want to scrub its current contents
if it does exist.

>
> fclose(fid);
> ==================================================
From: kees de Kapper on
Great! that works.

thnx.