[FUNCTION] GetFileLines(address, remove_blank_lines, trim_lines, keep_newline_char) (1 Viewer)

BlueIshDan

☠
Local time
Today, 04:31
Joined
May 15, 2014
Messages
1,122
This function will return the contents of a file in a string array.
It provides you with the following options:
- removal of blank lines
- trimming of spaces at end of lines
- keeping the newline character at the end of the line.

Code:
' Reference Microsoft Scriping Runtime     
   
Public Function GetFileLines(ByVal address As String, _
                             ByVal remove_blank_lines As Boolean, _
                             ByVal trim_lines As Boolean, _
                             ByVal keep_newline_char)
    
    ' keep_newline_char represents the Chr(byte) value of 10 and 13. These Bytes represent a NewLine.
    ' passing a true value to this parameter will cause returned lines to contain the new line value at the end of them.
    ' Use: True - Displaying data in a message
    '      False - Parsing the data line by line.
    
                             
    Dim fs As New FileSystemObject
    
    Dim arr_bytes() As Byte
    Dim file_node As Long

    Dim lines() As String
    Dim line_count As Long: line_count = 0
    
    ReDim lines(line_count)
        
    If fs.FileExists(address) Then
    
        ReDim arr_bytes(FileLen(address))
        file_node = FreeFile
        
        Open address For Binary Access Read As file_node
            Get 1, , arr_bytes
        Close file_node
        
        
        For Each var_byte In arr_bytes
            
            If var_byte = 10 Or var_byte = 13 Then
                If trim_lines Then: lines(line_count) = Trim(lines(line_count))
                
                If remove_blank_lines And Trim(lines(line_count)) = "" Then
                    lines(line_count) = ""
                Else
                    If keep_newline_char Then: lines(line_count) = lines(line_count) & Chr(var_byte)
                    line_count = line_count + 1
                    ReDim Preserve lines(line_count)
                End If
                
            Else
                lines(line_count) = lines(line_count) & Chr(var_byte)
            End If
            
            var_byte = Empty
            
        Next
        
    End If
    
    ' If your last result is wonky, focus on the following line. It was a quick fix for me :)
    lines(line_count) = Left(lines(line_count), Len(lines(line_count)) - 1)

    ReDim arr_bytes(0)
    Set fs = Nothing
    file_node = Empty
    line_count = Empty
    
    GetFileLines = lines
    
    ReDim lines(0)
    
End Function
 
Last edited:

Users who are viewing this thread

Top Bottom