How can I keep track of a constantly updating text file's latest string

9 views (last 30 days)
I'm currently new to matlab and would appreciate some help with my current code. I'm currently constantly updating a text file saved in the same spot as the code that is opening it. The updating is being done with Unity and involves constantly updating the most recent console logs to the text file. Is there any way I could continuously keep track of the latest log in a variable or something?
If it helps, this is how my current text file is set up. Basically my unity code constantly adds logs below the last log.

Accepted Answer

Voss
Voss on 27 Mar 2024
The following function returns a string containing the last non-empty line of text in the file (or "" if there are none).
Call it by passing in the name of your text file whenever you want to see what the latest event is.
As for checking in synchrony with Unity, I don't know.
As for "continuously" checking, you could call this function in a while loop, e.g., this would keep checking until an event starting with "escape" is the latest event:
evt = "";
while ~startsWith(evt,"escape")
evt = get_latest_event(filename);
end
But note that nothing would prevent multiple events from being written to the file in between the times when you check it, so you could miss the event you're looking for, i.e., the event happens but it's not ever the last event in the file when you check.
function out = get_latest_event(filename)
L = readlines(filename)
idx = numel(L);
if idx == 0
out = "";
return
end
while idx > 0
out = L(idx);
if ~strcmp(out,"")
return
end
idx = idx-1;
end
end
  2 Comments
Geoffrey
Geoffrey on 28 Mar 2024
Thanks for the explanation and example code. I'll try and see what I can do!
Voss
Voss on 28 Mar 2024
You're welcome!
It occurred to me after I wrote my answer that the text file might be very large, and if that's the case, then a different approach (not reading the entire file with readlines) will be faster. Something like this:
function out = get_latest_event(filename)
fid = fopen(filename,'rt');
fseek(fid,0,'eof');
filesize = ftell(fid);
offset = min(100,filesize);
while true
fseek(fid,-offset,'eof');
txt = deblank(fread(fid,[1 Inf],'*char'));
if any(txt == newline()) || offset == filesize
break
end
offset = min(offset+100,filesize);
end
fclose(fid);
if isempty(txt)
out = "";
else
out = string(regexp(txt,'([^\r\n]+)$','tokens','once'));
end
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!