%% Append To or Overwrite Existing Text Files
% This example shows how to append values to an existing text file, rewrite the entire file, and overwrite only a portion of 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.
%
%% Append to Existing Text File
% Create a file named changing.txt.

fileID = fopen('changing.txt','w');
fmt = '%5d %5d %5d %5d\n';
fprintf(fileID,fmt, magic(4));
fclose(fileID);

% The current contents of changing.txt are:
% 16     5     9     4
%  2    11     7    14
%  3    10     6    15
% 13     8    12     1
%
% Open the file with permission to append.

fileID = fopen('changing.txt','a');

%
% Write the values [55 55 55 55] at the end of file:

fprintf(fileID,fmt,[55 55 55 55]);

%
% Close the file.

fclose(fileID);

%
% View the contents of the file using the type function.

type changing.txt

%
%% Overwrite Entire Text File
% A text file consists of a contiguous set of characters, including newline characters. To replace a line of the file with a different number of characters, you must rewrite the line that you want to change and all subsequent lines in the file.
% Replace the first line of changing.txt with longer, descriptive text. Because the change applies to the first line, rewrite the entire file.

replaceLine = 1;
numLines = 5;
newText = 'This file originally contained a magic square';

fileID = fopen('changing.txt','r');
mydata = cell(1, numLines);
for k = 1:numLines
   mydata{k} = fgetl(fileID);
end
fclose(fileID);

mydata{replaceLine} = newText;

fileID = fopen('changing.txt','w');
fprintf(fileID,'%s\n',mydata{:});
fclose(fileID);

%
% View the contents of the file.

type changing.txt

%
%% Overwrite Portion of Text File
% Replace the third line of changing.txt with [33 33 33 33]. If you want to replace a portion of a text file with exactly the same number of characters, you do not need to rewrite any other lines in the file.

replaceLine = 3;
myformat = '%5d %5d %5d %5d\n';
newData = [33 33 33 33];

%
% Move the file position marker to the correct line.

fileID = fopen('changing.txt','r+');
for k=1:(replaceLine-1);
   fgetl(fileID);
end

%
% Call fseek between read and write operations.

fseek(fileID,0,'cof');

fprintf(fileID, myformat, newData);
fclose(fileID);

%
% View the contents of the file.

type changing.txt

% Copyright 2012 The MathWorks, Inc.