MATLAB: Append data at the beginning of a file MATLAB

append file write

Hi, please how can fopen be used to append data at the beginning of the file ? like a header.
thank-you

Best Answer

You cannot insert characters in front of a file directly. This is a limitation of the file systems and not a problem of Matlab and not a task for FOPEN. So you have to read the complete file at first, add the new characters in the memory and (over)write a new file:
S = fileread(FileName);
S = ['Your header line', char(10), S];
FID = fopen(FileName, 'w');
if FID == -1, error('Cannot open file %s', FileName); end
fwrite(FID, S, 'char');
fclose(FID);
There should be an equivalent process using a memory mapped file. I'm not sure if internally exactly the same is performed, such that there is no difference is the speed. But I assume if the files contains several GigaBytes, the memory mapped method should be better.