MATLAB: Passing formatted string output of sprintf to fprintf


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?

Best Answer

  • 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);