delete last line of a .txt
15 次查看(过去 30 天)
显示 更早的评论
How I can delete the last line from text file every 5 minutes
0 个评论
回答(2 个)
Guillaume
2014-11-12
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 个评论
Luuk van Oosten
2014-11-12
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!