How to write literal text from character array to a file

61 views (last 30 days)
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?

Answers (2)

Guillaume on 11 Nov 2014
fprintf('%s', chararray)
should work
Guillaume on 13 Nov 2014
Edited: Guillaume on 13 Nov 2014
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')
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.

Sign in to comment.

Richard Zapor
Richard Zapor on 20 Nov 2021
Use fwrite.


Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!