%% Overwrite or Append to an Existing Binary File
% This example shows how to overwrite a portion of an existing binary file and append values to the file.
% By default, fopen opens files with read access. To change the type of file access, use the permission specifier in the call to fopen. Possible permission specifiers include:
% 'r' for reading
% 'w' for writing, discarding any existing contents of the file
% 'a' for appending to the end of an existing file
% To open a file for both reading and writing or appending, attach a plus sign to the permission, such as 'w+' or 'a+'. If you open a file for both reading and writing, you must call fseek or frewind between read and write operations.
%
%% Overwrite a Portion of an Existing File
% Create a file named magic4.bin, specifying permission to write and read.

fileID = fopen('magic4.bin','w+');
fwrite(fileID,magic(4));

% The original magic(4) matrix is:
% 16     2     3    13
%  5    11    10     8
%  9     7     6    12
%  4    14    15     1
% The file contains 16 bytes, 1 for each value in the matrix.
%
% Replace the values in the second column of the matrix with the vector, [44 44 44 44]. To do this, first seek to the fourth byte from the beginning of the file using fseek.

fseek(fileID,4,'bof');

%
% Write the vector [44 44 44 44] using fwrite.

fwrite(fileID,[44 44 44 44]);

%
% Read the results from the file into a 4-by-4 matrix.

frewind(fileID);
newdata = fread(fileID,[4,4])

%
% Close the file.

fclose(fileID);

%
%% Append Binary Data to Existing File
% Append the values [55 55 55 55] to magic4.bin. First. open the file with permission to append and read.

fileID = fopen('magic4.bin','a+');

%
% Write values at end of file.

fwrite(fileID,[55 55 55 55]);

%
% Read the results from the file into a 4-by-5 matrix.

frewind(fileID);
appended = fread(fileID, [4,5])

%
% Close the file.

fclose(fileID);

% Copyright 2012 The MathWorks, Inc.