problem when write first line to text file
2 ビュー (過去 30 日間)
古いコメントを表示
hi: I met some problem when tried to write the first line to text file. below is what the base test file was.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/161383/image.jpeg)
I use the command:
fid = fopen('test.txt','r+')
fprintf(fid,'%s\n','abc');
fclose(fid)
but the result becomes like below:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/161384/image.jpeg)
the first number is deleted.but I could not find why.
could anyone give me some suggestions?
thanks! Li
1 件のコメント
KSSV
2017 年 3 月 6 日
I think you cannot write in first line. Better read the content and write to a new text file with first line of your choice.
採用された回答
Jan
2017 年 3 月 6 日
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);
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!