User Tools

Site Tools


vbs:lastlinesoftextfile

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
vbs:lastlinesoftextfile [2013/01/24 09:50]
rlunaro
vbs:lastlinesoftextfile [2014/12/24 10:42] (current)
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, ​ byval lastLines )
 +    dim fso 
 +    dim file 
 +    dim lines()
 +    dim linenum
 +    dim lastWrittenLine
 +    dim out
 +
 +    set fso = createobject( "​scripting.filesystemObject"​ ) 
 +    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) <> ""​ then
 +                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
 +
 +</​code>​
  
vbs/lastlinesoftextfile.txt ยท Last modified: 2014/12/24 10:42 (external edit)