delete last line of a .txt

17 visualizaciones (últimos 30 días)
shamsa
shamsa el 12 de Nov. de 2014
Respondida: Luuk van Oosten el 12 de Nov. de 2014
How I can delete the last line from text file every 5 minutes

Respuestas (2)

Guillaume
Guillaume el 12 de Nov. de 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.

Luuk van Oosten
Luuk van Oosten el 12 de Nov. de 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

Categorías

Más información sobre Text Data Preparation en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by