help 中有这样一段内容 Exporting to Text Data Files
如下:
the contents of the file:
16 5 9 4
2 11 7 14
3 10 6 15
13 8 12 1
55 55 55 55
Example — Overwriting an Existing Text File. Replace the third line of the file changing.txt from the previous example with [33 33 33 33]:
replaceLine = 3;
myformat = '%5d %5d %5d %5d\n';
% Open the file with permission to read and update.
% Use fgetl, which reads a line at a time,
% to place the file position indicator at the third line.
fid = fopen('changing.txt','r+');
for k=1:(replaceLine-1);
fgetl(fid);
end;
% call fseek between read and write operations
fseek(fid, 0, 'cof');
% print the new values
fprintf(fid, myformat, [33 33 33 33]);
% close the file
fclose(fid);
To view the file, use the type function:
type changing.txt
This command returns the new contents of the file:
16 5 9 4
2 11 7 14
33 33 33 33
13 8 12 1
55 55 55 55 |