MATLAB: Problem when write first line to text file

fprintf first line of text file

hi: I met some problem when tried to write the first line to text file. below is what the base test file was.
I use the command:
fid = fopen('test.txt','r+')
fprintf(fid,'%s\n','abc');
fclose(fid)
but the result becomes like below:
the first number is deleted.but I could not find why.
could anyone give me some suggestions?
thanks! Li

Best Answer

You cannot insert characters in a text file. Trying this will overwrite the existing characters. Therefore you have to read the complete file at first, add the string in the memory and write the complete file afterwards:
Str = fileread('test.txt');
fid = fopen('text.txt', 'w');
if fid == -1
error('Cannot open file for writing.');
end
fprintf(fid,'%s\n','abc');
fprintf(fid, '%s', Str); % Or faster: fwrite(fid, Str, 'char');
fclose(fid);