|
|
|
| 1 March 2002 | GetLines() |
| Author | W.M. Hinsch (New Mexico Mark) |
| Action | Gets a line or range of lines from a text file. |
| Syntax | GetLines (FileSpec [,FirstLine] [,LastLine]) |
| Parameters | |
| Remarks | This uses the file system object, so file size is limited by speed, not memory (Although lines returned is limited by memory). Lines may be returned in reverse order simply by specifying the higher line number first. |
| Returns | Returns an array with the first line in element 0 and the last line in element abs(last-first). If either line exceeds the number of lines in the file, the array will be truncated to the actual number of valid lines returned. I.e. If a file contains 100 lines and 90-110 are requested, the returned array will have 11 elements with lines 90-100 in those elements. The function raises an error of -1 if it cannot instantiate the file system object or open the file. In this case, a one-element array (with empty string) will be returned. |
| Dependencies | Uses the file system object. |
| Examples |
;Examples
$TFile = 'c:\test.txt'
IF Open(1,$TFile,5) = 0
FOR $i = 1 TO 100
$RC=WriteLine(1,'Line '+$i+@CRLF)
NEXT
$RC=Close(1)
$aTmp=GetLines($TFile) ; Get line 1 by default
$aTmp[0] ? ?
$aTmp=GetLines($TFile,1,5) ; Get lines 1-5
FOR EACH $j IN $aTmp $j ? NEXT ?
$aTmp=GetLines($TFile,50,45) ; Get lines 50-45
FOR EACH $j IN $aTmp $j ? NEXT ?
$aTmp=GetLines($TFile,95,105) ; Attempt to get lines 95-105
FOR EACH $j IN $aTmp $j ? NEXT ?
$aTmp=GetLines($TFile,110,115) ; Attempt to get lines 110-115
FOR EACH $j IN $aTmp $j ? NEXT ?
$aTmp=GetLines($TFile,100) ; Get line 100
$aTmp[0] ? ?
IF Exist($TFile)
DEL $TFile
ENDIF
ENDIF
;Console displays
;Line 1
;Line 1
;Line 2
;Line 3
;Line 4
;Line 5
;Line 50
;Line 49
;Line 48
;Line 47
;Line 46
;Line 45
;Line 95
;Line 96
;Line 97
;Line 98
;Line 99
;Line 100
;Line 100
|
| Source |
FUNCTION GetLines ($sfilespec, OPTIONAL $ifirst, OPTIONAL $ilast)
DIM $i, $ipos, $vtmp, $istep, $ofs, $otextstream
$sfilespec=''+$sfilespec
$ifirst=0+$ifirst
$ilast=0+$ilast
$istep=1
REDIM $getlines[0]
$getlines[0]=''
IF Exist($sfilespec)
IF ($ifirst <= 0)
$ifirst=1
ENDIF
IF ($ilast <= 0)
$ilast=$ifirst
ENDIF
$ipos = 0
IF ($ifirst > $ilast)
$vtmp=$ifirst ; -swap-
$ifirst=$ilast
$ilast=$vtmp
;
$istep=-1
$ipos=$ilast-$ifirst
ENDIF
$ofs=CreateObject('Scripting.FileSystemObject')
IF @error
EXIT -1
ENDIF
$otextstream=$ofs.opentextfile($sfilespec,1)
IF @error
EXIT -1
ENDIF
REDIM $getlines[$ilast-$ifirst]
FOR $i = 0 TO UBound($getlines)
$getlines[$i]=''
NEXT
; Position the pointer to the first line to be read into the array
$i=1
WHILE $i < $ifirst AND @error = 0
$i=$i+1
$otextstream.skipline
LOOP
; Read lines into the array.
WHILE $i <= $ilast AND @error = 0
$getlines[$ipos]=$otextstream.readline
$ipos=$ipos+$istep
$i=$i+1
LOOP
IF @error
IF ($ipos < 2)
$ipos=2
ENDIF
REDIM PRESERVE $getlines[$ipos-2]
ENDIF
$otextstream.close
ELSE
EXIT -1
ENDIF
ENDFUNCTION ; - GetLines -
|
|
|
|