delete last line of a .txt
22 views (last 30 days)
Show older comments
How I can delete the last line from text file every 5 minutes
0 Comments
Answers (2)
Guillaume
on 12 Nov 2014
Use a timer to schedule the execution of your deletion code every 5 minutes. Note that if matlab is too busy to process events, the timer may not be called until matlab is less busy. There's no way around that since matlab is single threaded.
There is actually no way in matlab to simply truncate a file. You have two options:
1. Read the entire content of the file and rewrite bar the last line. That's probably not going to be fast.
fcontent = fileread('somefile.txt');
fid = fopen('somefile.txt', 'wt');
fwrite(fid, regexp(fcontent, '.*(?=\n.*?)', 'match', 'once'));
fclose(fid);
2. Figure out the length the file should be without the last line (possibly using fopen, fgetl and ftell), and use this submission from the FEX to truncate the file to that length.
0 Comments
Luuk van Oosten
on 12 Nov 2014
A while ago I used something that might help you with getting the total amounts of lines in your file; If you then follow Guilaumes directions, you will find your answer.
fid = fopen('YourData.txt','r');
fseek(fid, 0, 'eof');
chunksize = ftell(fid);
fseek(fid, 0, 'bof');
ch = fread(fid, chunksize, '*uchar');
k = sum(ch == sprintf('\n')); % k is number of lines
fclose(fid)1
0 Comments
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!