MATLAB Answers

append data...it doesnt change line

조회 수: 9(최근 30일)
Andrew
Andrew 26 Jun 2013
i want to open the 33.txt go to the end of the file add the number 4 ,change line and etc etc...
clc
for k=1:1:5;
fid=fopen('C:\Users\Mr Andrew\Desktop\33.txt','a');
fprintf(fid,'4 \n')
end
what is my error ? my code doesnt change line... thank you

  댓글 수: 0

로그인 to comment.

채택된 답변

Tom
Tom 26 Jun 2013
try adding a carriage return as well:
fprintf(fid,'4 \r\n')
I'd also recommend using fclose(fid) each time you've finished with the file

  댓글 수: 3

Jan
Jan 26 Jun 2013
This is a benefit, when you open the file with Windows' Notepad, but all other editors I've seen in the last 12 years understand the line breaks of the other systems perfectly. So I recommend to avoid using Notepad instead of adjusting the text files for one stubborn program.
Andrew
Andrew 27 Jun 2013
thank you!
with \r it worked!!!!
Tom
Tom 27 Jun 2013
for what it's worth, Jan is correct about this being a Notepad issue - if you just use '\n' and open it within MATLAB, it appears on a new line.

로그인 to comment.

More Answers (2)

Image Analyst
Image Analyst 26 Jun 2013
Why is fopen inside the loop? You aren't showing all your real code but chances are that you want it before the loop, not inside it. Also, add an fclose after the loop.

  댓글 수: 1

Andrew
Andrew 27 Jun 2013
thank you!

로그인 to comment.


Jan
Jan 26 Jun 2013
The data is written, when the file is closed:
fid = fopen('C:\Users\Mr Andrew\Desktop\33.txt', 'a');
for k = 1:5
fprintf(fid,'4 \n')
end
fclose(fid); % close the file!

  댓글 수: 2

Andrew
Andrew 27 Jun 2013
your code Jan Simon doesnt change line....i tried this
clc
fid = fopen('C:\Users\Mr Andrew\Desktop\33.txt', 'a');
for k = 1:5
fprintf(fid,'343453534 \r\n') % i add \r
end
fclose(fid);
and it is working!!! thank you Jan Simon and Tom!
Jan
Jan 27 Jun 2013
The text file created by my program is correct and understood by almost all editors. Only Notepad fails, but this is a problem of Notepad, not of the file.
Bit inserting the \r explicitly causes traoubles under e.g. older versions of XEmacs, the TeX interpreter, Matlab until version 6.5 under Linux, etc. Therefore the most efficient solution is relying on '\n' and omitting the usage of the dull Notepad (Notepad++ from the net is much smarter!).
Another method to create the old DOS linebreaks under Windows: Open the file in text-mode:
fopen(FileName, 'at')
Then fprintf(fid, '\n') writes \r\n autoamtically. But this can have strange side effects, like using the End-Of-File character accidently and the number of characters will differ from the number of bytes.

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by