Passing formatted string output of sprintf to fprintf
8 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Image Analyst
2020 年 5 月 11 日
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
その他の回答 (1 件)
Steven Lord
2020 年 5 月 11 日
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 件のコメント
Steven Lord
2020 年 5 月 13 日
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.
参考
カテゴリ
Help Center および File Exchange で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!