Sign in to follow this  
Followers 0
cheesestain

Read a certain amount of lines from text file

4 posts in this topic

How do I read a specified number of lines from a text file?

Share this post


Link to post
Share on other sites



Or FileRead, then find the desired linebreak using StringInStr, the StringLeft to get everything before that linebreak.

Or FileReadToArray, then Redim at the desired line.

Technically Jos' solution is the only one that only reads the specified number of lines from the file (as opposed to reading everything and then discarding the excess), but for a larger amount of lines I assume these alternatives will be faster.

If you do use FileReadLine in a loop, make sure to pass it a handle from FileOpen, then FileClose it when you are done. Otherwise the file will be opened and closed for each line you read.

Share this post


Link to post
Share on other sites

Depending on you line termination type this will return 20 lines if lines end in Unix LF or 10 if lines end in Window CR LF:

$file = FileOpen("C:\test.txt", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

$filewhole = FileRead($file)

FileClose($file)

$nOffset = 1

While 1
    $array = StringRegExp($filewhole, '^(.*?[\r?\n]){20}', 2, $nOffset)

    If @error = 0 Then
        $nOffset = @extended
    Else
        ExitLoop
    EndIf
    For $i = 0 To UBound($array) - 1
        MsgBox(0, "RegExp Test with Option 2 - " & $i, $array[$i])
    Next
WEnd

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0