How do I print a % character into a file
조회 수: 8 (최근 30일)
이전 댓글 표시
I am creating an app in App Designer, creating an output file that will be an .m file for another user to run later.
I'd like to put a comment header at the start of this file but I can't double excape the % character
app.SessionFile = fopen(app.SessionFileName,'at');
str = sprintf("%% Parameters: %c%u...",v1,v2...); % Put required string into str - works
str is now "% Paramters: ...." but it won't go out to the file with
fprintf(app.SessionFile,str); % Nothing gets printed, comment gets stripped out!
(0 chars printed)
Also not working
str = sprintf("%%% Parameters:
str = sprintf(" %% Parameters:
Seems like if I have a string I want to put in a text file MatLab shouldn't mess with it.
Also: is 'at' the same as 'wt' ? seems like it always appends anyway with fprint.
댓글 수: 3
Walter Roberson
2024년 9월 14일
fprintf(MyFile, "%s", "%")
or
fwrite(MyFile, "%s")
Again I caution that neither version of those will add a newline.
채택된 답변
추가 답변 (2개)
Steven Lord
2024년 9월 13일
If you don't need str inside your code other than to write it to the file, rather than creating it just write directly to the file.
app.SessionFile = fopen(app.SessionFileName,'at');
fprintf(app.SessionFile,"%% Parameters: %c%u...",v1,v2...);
댓글 수: 0
Walter Roberson
2024년 9월 13일
Either
fprintf(app.SessionFile,"%s",str);
or
fwrite(app.SessionFile, str);
Note: your str does not appear to include newline. Neither of the above possibilities will insert a newline. The easiest way to include a newline is
fprintf(app.SessionFile,"%s\n",str);
댓글 수: 4
Walter Roberson
2024년 9월 16일
편집: Walter Roberson
2024년 9월 16일
fprintf(MyFile,str) treats str as the format, an interprets it, scanning it looking for % formats.
fprintf(MyFile, "%s", str) treats %s as the format, and treats str as the text to be inserted literally.
There is no special documentation for fprintf(MyFile,str) because it is just treated as an instance of fprintf(fileID,formatSpec,A1,...,An) with str as the formatSpec and with no A1,...,An
If you write an unterminated line to a file and close the file, then the line will be inserted into the file, and the file will just end there; the line can be pulled out of the file normally. It is possible some common DOS utilities might not show the trailing line.
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!