Using fprintf to write to multiple files simultaneously
Mostrar comentarios más antiguos
I want to write the same text to the screen and in to a file. So I have to double the code:
fprintf('this is some text with numbers: %d, %d', x,y);
fprintf(fid, 'this is some text with numbers: %d, %d', x,y);
Alternatively I can introduce a text string to avoid double code:
str = sprintf('this is some text with numbers: %d, %d', x,y);
fprintf(str);
fprintf(fid, str);
But obviously it does not work to use fprintf to write to mutliple files simultaneously? Would be nice if possible.
fprintf([1 fid],'this is some text with numbers: %d, %d', x,y);
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 9 de Abr. de 2020
3 votos
You are correct, any one fprintf() can only write to one place at a time.
You should have a look at diary
3 comentarios
Lionel Trebuchon
el 26 de Jul. de 2022
Hello Walter!
Do you know of a functionality (even hidden/undocumented) to write diaries/logs to two locations simultaneously? The code of diary is hidden to us.
The context is a slightly unstable system, and we want to enhance our chances to access the logs one way or the other.
We would rather prefer not to brute-force, i.e. copy the full logs, as they can get quite long.
Thanks!
Best, Lionel
Steven Lord
el 26 de Jul. de 2022
You could try launching MATLAB with the -logfile option and also call diary in that session. The two files won't be exactly the same but they may be close enough for your purposes.
But for problems like the original question and for this, if I wanted to log information to multiple places I'd write a function that I could call with a vector of file identifiers (and potentially some "dummy" identifier if I wanted to write to the screen as well) that would write to all those locations.
function logToFilesAndScreen(fid, varargin)
% logToFilesAndScreen Write text to one or more files and to the screen
%
% logToFilesAndScreen(fid, varargin) writes the information stored in
% varargin (which must contain valid inputs to the fprintf function when
% passed to it as a comma-separated list) to the screen and to all the
% files whose file IDs (as opened using fopen) are passed in as the fid
% input.
% Print to screen
fprintf(varargin{:})
% Print to file(s)
for whichfile = 1:numel(fid)
fprintf(fid(whichfile), varargin{:})
end
end
Walter Roberson
el 26 de Jul. de 2022
Editada: Walter Roberson
el 26 de Jul. de 2022
Note: identifier 1 always writes to the screen (well, unless MATLAB has been run in non-interactive mode.)
Categorías
Más información sobre Entering Commands en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!