Newline in text files

조회 수: 58 (최근 30일)
Florian
Florian 2020년 11월 25일
댓글: Florian 2020년 11월 25일
Hi!
I am very sorry to post this question, because it has already been answered multiple times in this forum. Unfortunately, the presented solution doesn't work for me. So, I am wondering what's going wrong.
I want to write some parameters in a .tex file. Following the hints in the mentioned posts, I opened my testfile with the option 'wt' to make sure that my newlines '\n' are recognized
fid1 = fopen('Testfile.txt','wt');
fprintf(fid1,'%s','abc');
fprintf(fid1,'%s','\n');
fprintf(fid1,'%s','def');
fprintf(fid1,'%s','\n');
fprintf(fid1,'%s','ghi \n jkl');
fclose(fid1);
But, independently of what I do, I obtain
abc\ndef\nghi \n klm
once I open 'Testfile.txt'.
Opening the file with 'w' and using additonally '\r' doesn't work either.
So, I am grateful for any hints that might help solving the problem!
Thank you in advance!
  댓글 수: 2
Stephen23
Stephen23 2020년 11월 25일
편집: Stephen23 2020년 11월 25일
"...to make sure that my newlines '\n' are recognized"
Your code does not have any newlines.
The character vector '\n' consists of a backslash and an 'n' character, and your fprintf calls, e.g.
fprintf(fid1,'%s','\n');
simply print that input string literally, so you get '\n' in the file (i.e. a backslash followed by an 'n').
If you want to interpret the characters '\n' as a newline, then they must be in the format string itself, e.g.:
fprintf(fid1,'%s\n','blah');
will print the text 'blah' followed by a newline (if using text mode appropriately selected to suit the OS).
It is not clear to me how your question is related to .tex files, or how TeX is related to this in any way.
Florian
Florian 2020년 11월 25일
Oh - I undestand. Thank you!
There is no relation to TeX files - there was just the 't' missing in the subject.
Thank you for pointing this out!

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

채택된 답변

Bjorn Gustavsson
Bjorn Gustavsson 2020년 11월 25일
When I want to explicitly write \n for new-line I include it explicitly in the string-specification:
fid1 = fopen('Testfile.txt','wt');
fprintf(fid1,'%s\n','abc');
fprintf(fid1,'%s\n','def');
fprintf(fid1,'%s\n%s','ghi','jkl');
fclose(fid1);
But since you write to a .tex-file this is only important if you do it in some environment like verbatim that will respect the new-lines for the output. Otherwise you could run with \\, depending on how that is propagating to the .tex-file you might have to have 4 consecutive \ to get \\ written to file.
HTH
  댓글 수: 1
Florian
Florian 2020년 11월 25일
Great! Thank you very much!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by