write string in text file

조회 수: 544 (최근 30일)
Ronaldo
Ronaldo 2013년 12월 24일
이동: Stephen23 2022년 9월 5일
How can I write some strings in text file (each strinng in one line)? example:
Happy
New
Year

채택된 답변

Image Analyst
Image Analyst 2013년 12월 24일
편집: Image Analyst 2013년 12월 27일
Try this:
fid = fopen('ny.txt','wt');
fprintf(fid, 'Happy\nNew\nYear');
fclose(fid);
  댓글 수: 3
Ronaldo
Ronaldo 2013년 12월 27일
The last line must be changed to:
fclose(fid);
Image Analyst
Image Analyst 2013년 12월 27일
Right Ronaldo - thanks for noticing and correcting. I've edited and corrected.

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

추가 답변 (5개)

cui,xingxing
cui,xingxing 2022년 9월 5일
이동: Stephen23 2022년 9월 5일
hi, if you use latest matlab 2022a, you can use new matlab build-in function WRITELINES

Walter Roberson
Walter Roberson 2013년 12월 24일
fid = fopen('ny.txt','wt');
fprintf(fid, 'Happy\New\n');
fprintf(fid,, 'Year\n');
fclose(fid)
  댓글 수: 2
Ronaldo
Ronaldo 2013년 12월 24일
What I see in the text file is
HappyYear
What I want to see is
Happy
Year
Ronaldo
Ronaldo 2013년 12월 24일
편집: Ronaldo 2013년 12월 27일
The correct one is
fid = fopen('ny.txt','wt');
fprintf(fid, 'Happy\n');
fprintf(fid, 'New\n');
fprintf(fid, 'Year\n');
fclose(fid)
Anyway, so many thanks for your great help.

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


Dinesh Satelkar
Dinesh Satelkar 2017년 2월 9일
How i can write extracted text in text file

Ali
Ali 2017년 8월 3일
Is there a way to use save function to do that simple job? I could never get why an intuitive write in matlab needs such an un-intuitive function F-Print-F.
  댓글 수: 1
Image Analyst
Image Analyst 2017년 8월 3일
That's just the name of it. It matches the name used in other languages like C, Java, etc. The save() function does not write custom formatted strings out to a text file like fprintf() does. The save() function saves variables in a binary, proprietary fashion.

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


Ali
Ali 2017년 8월 3일
편집: Ali 2017년 8월 3일
Thanks for the comments. Save has a -ascii option which is supposed to do what I need. But now that you know about matlab, could you please comment on my question here: write multiple lines of text into a text file ?
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 8월 3일
"Each variable must be a two-dimensional double array."
Character strings are not double array. double() of the string is done internally and that is written, getting back results such as
1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02 9.2000000e+01 1.1000000e+02 1.1900000e+02 1.1100000e+02 1.1400000e+02 1.0800000e+02 1.0000000e+02
for 'hello\nworld'

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

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by