vbs:lastlinesoftextfile
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| vbs:lastlinesoftextfile [2013/01/24 08:50] – rlunaro | vbs:lastlinesoftextfile [2022/12/02 21:02] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Read the Last Lines of a Text File ====== | ||
| + | |||
| + | The program works smoothly even on files of twenty thousand lines. It simply read lines, keeping in memory the last N lines. When it reaches the end of the stream, it return the last N lines kept. | ||
| + | |||
| + | <code visual basic> | ||
| + | ' read all the content of a log file and | ||
| + | ' put it into a string. | ||
| + | function log2str( byval filename, | ||
| + | dim fso | ||
| + | dim file | ||
| + | dim lines() | ||
| + | dim linenum | ||
| + | dim lastWrittenLine | ||
| + | dim out | ||
| + | |||
| + | set fso = createobject( " | ||
| + | set file = fso.openTextFile( filename ) | ||
| + | redim lines(lastLines) | ||
| + | linenum = 0 | ||
| + | lastWrittenLine = -1 | ||
| + | do while not file.atEndOfStream | ||
| + | lines( linenum ) = file.readLine | ||
| + | lastWrittenLine = linenum | ||
| + | linenum = (linenum + 1 ) mod lastLines | ||
| + | loop ' not file.atEndOfStream | ||
| + | |||
| + | if lastWrittenLine > 0 then | ||
| + | linenum = (lastWrittenLine + 1) mod lastLines | ||
| + | do | ||
| + | if lines(linenum) <> "" | ||
| + | out = out & lines(linenum) & vbCrLf | ||
| + | end if ' lines(linenum) <> "" | ||
| + | linenum = (linenum + 1 ) mod lastLines | ||
| + | loop until linenum = (lastWrittenLine + 1) | ||
| + | end if ' lastWrittenLine | ||
| + | | ||
| + | ' return all the content | ||
| + | log2str = out | ||
| + | | ||
| + | end function ' log2str | ||
| + | |||
| + | </ | ||
