필터 지우기
필터 지우기

How to write literal text from character array to a file

조회 수: 8 (최근 30일)
Charles Gallistel
Charles Gallistel 2014년 11월 11일
답변: Richard Zapor 2021년 11월 20일
I can easily read a Matlab script into a character array using readtextfile. How do I reverse the process? I want to write the character array to a text file, including all the % and \ characters that fprintf interprets as control characters. How do I suppress fprintf's interpreting the % and \ etc and get it to just write the literal text exactly as it appears in the character array and exactly as it appeared in the Matlab script that was read into the character array? Or is there some other output function that I should use?

답변 (2개)

Guillaume
Guillaume 2014년 11월 11일
fprintf('%s', chararray)
should work
  댓글 수: 4
per isakson
per isakson 2014년 11월 12일
Yes, it works. However, (in R2013a) the character array is not converted to a cell array and the trailing spaces are not "suppressed".
I tested with this script
char_array = char( randi([65,90], 4,12 ) );
char_array( 2:3, 9:12 ) = ' ';
cell_array = strcat( char_array );
for jj = 1:4
fprintf( '%d: %s\n', length(char_array(jj,:)),char_array(jj,:) )
end
fprintf('\n')
whos char_array cell_array
Output in the command window
12: KEXIUCOVQORU
12: BGYXKDBA
12: GKMJGYGB
12: DBMCKYJELEQU
Name Size Bytes Class Attributes
cell_array 4x12 96 char
char_array 4x12 96 char
>>
Guillaume
Guillaume 2014년 11월 13일
편집: Guillaume 2014년 11월 13일
@Charles,
fprintf('%s', chararray)
does not interpret any character in chararray including % and \. These characters are only interpreted in the format string,
>>fprintf('%s', 'A string with some % signs %d%f and \ characters \t\n')
returns
A string with some % signs %d%f and \ characters \t\n
I'll note that what you say works is exactly my answer with the addition of a \n control character in the format string. That addition, in no way modifies the behaviour of fprintf. With or without it, the string is interpreted the same way.

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


Richard Zapor
Richard Zapor 2021년 11월 20일
Use fwrite.
str='\a%s';
fileID=fopen('AllCharFile.txt','w')
fwrite(fileID,double(str));
fclose(fileID)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by