Skip to content
Advertisement

Matlab’s fwrite: What happens to skipped bytes?

Suppose I have the following code:

fid = fopen(my_filename,'w','ieee-le','ISO-8859-1');
fwrite(fid,1,'short',10,'ieee-le')

Then this would open an earlier specified file, skip the first 10 bytes and write 1 into the following two.

But what happens to the first 10 bytes, assuming the opened file did not exist before? If I were to access one, what would I end up getting and why?

Advertisement

Answer

From the POSIX documentation:

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

Thus, assuming MATLAB’s fwrite uses fseek to skip byes (which is highly likely), then the skipped bytes past the end of the file will be filled with zeros on any POSIX architecture (Linux, MacOS). This is not necessarily the case for Windows, which is not POSIX.

A quick test on MacOS confirms this behavior:

fn = 'test.bin';
fid = fopen(fn,'wb');
fwrite(fid,1,'uchar',10);
fclose(fid);
fid = fopen(fn,'r');
fread(fid,Inf,'uchar')
fclose(fid);

output:

ans =
     0
     0
     0
     0
     0
     0
     0
     0
     0
     0
     1
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement