problem when write first line to text file

조회 수: 2 (최근 30일)
Yu Li
Yu Li 2017년 3월 6일
댓글: Yu Li 2017년 3월 6일
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
  댓글 수: 1
KSSV
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
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);
  댓글 수: 1
Yu Li
Yu Li 2017년 3월 6일
thanks for your answer, my problem was solved!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Standard File Formats에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by