필터 지우기
필터 지우기

How to write to a text file several times without overwriting the old values

조회 수: 57 (최근 30일)
Erik
Erik 2011년 9월 19일
I write the output values from a simulation to a txt file using.
outputFile = fopen('output.txt','w'); fprintf(outputFile,'values');........
I would like to run the simulation several times with different output and store each simulation output without overwriting the old values. Is there some easy way to append the old values?

답변 (3개)

Tigersnooze
Tigersnooze 2011년 9월 19일
I think if you do
outputFile = fopen('output.txt', 'a+');
It would work when put in a loop. 'a' will append, where 'w' will discard existing contents.

the cyclist
the cyclist 2011년 9월 19일
One way:
for nf = 1:3
% Other stuff
outputFile = fopen(['output',num2str(nf),'.txt'],'w');
fprintf(outputFile,'values');
end
  댓글 수: 1
the cyclist
the cyclist 2011년 9월 20일
I didn't read your question carefully enough. My method will create multiple output files, not one file with appended data.

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


Walter Roberson
Walter Roberson 2011년 9월 19일
You want to append the old values after the new ones, or you want to append the new values after the old?
Appending the old values after the new requires opening the file with 'a+' access, seeking to the beginning of the file with fseek(fid,0,0), reading and recording the old values, seeking back to the beginning of the file, writing the new values, then writing the recorded old values. There is no built-in mechanism to "insert" text "moving over" the existing text automatically.
Appending the new values after the old values requires opening the file with 'a' or 'a+' access, and writing the new values. This is easier and more robust.

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by