Passing formatted string output of sprintf to fprintf
9 views (last 30 days)
Show older comments
I have a writeToLog function which takes formatted string and uses fprintf to print the formated string to both a log file and to a command window.
When I use fprintf to print a file location by passing file directory directly, it works perfectly:
dir = '\\file_server\parent_dir\sub_dir';
fprintf('Saving the log file to: %s\n', dir))
However, when I pass the formated string output of sprintf to fprintf, it errors out:
format_str = sprintf('Saving the log file to: %s\n', dir)
>> fprintf(format_str)
Warning: Escaped character '\p' is not valid. See 'doc sprintf' for supported special characters.
Saving the log file to: \file_server>>
Is there a way for fprintf to print the formatted string as is?
2 Comments
Accepted Answer
Image Analyst
on 11 May 2020
You'll need to do
function writeToLog(fid, formatted_str)
% Write to log file.
fprintf(fid, '%s\n', formatted_str);
% Print to command window.
fprintf('%s\n', formatted_str);
end
More Answers (1)
Steven Lord
on 11 May 2020
format_str = sprintf('Saving the log file to: %s\n', dir)
>> fprintf('%s', format_str)
You don't want to use the string created by sprintf as the format specifier, you want to use it as data with the '%s' format specifier.
BTW, you may want to use a different variable name to contain the name of your directory. dir already has a meaning in MATLAB.
3 Comments
Steven Lord
on 13 May 2020
If the second input to writeToLog has always passed through sprintf, it's always going to be text (either a char or string array.) So tell fprintf that just like Image Analyst suggested.
See Also
Categories
Find more on File Operations 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!