Diary Matlab :: Latest messages on top of the text file instead of append to bottom of file

172 views Asked by At

The diary function works well for logging purposes in my application, but instead of latest messages appearing on top of the text file ( this is the way I need it) it appends to older messages.

Any method to pre-append the messages rather than append to older messages in the text file or workarounds ?

1

There are 1 answers

0
Daniel On

Flipping the order should be done in the UI, here no HDD interaction is involved which will make it much faster.

At some point you need to open the logfile and initialize your data structure:

fid = fopen('fgetl.m');
lines = {}

Now read only the new lines. Repeat this cyclic:

tline = fgetl(fid);
new_line=false;
while ischar(tline)
    lines{end+1} = fgetl(fid);
    new_line=true
end

To display I recommend to display only the last n (choose a value) lines in your UI to avoid slowing down when the log grows:

if new_line
    reversed=lines(end:-1:max(numel(lines)-n+1,1));
    %update your UI here with the text in reversed
end

Finally, at the end of your program you need to close the file:

fclose(fid);