简单 - 将文件读入数组

时间:2010-03-14 16:49:08

标签: arrays file vb6

所以我有一个.dat文件,它只包含一个名字列表,每个名字都在一个新行上。我有一天完整的心理空白,但我如何从文件中取出这些名称并将它们放入数组中。

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

你应该读这个 http://www.visualbasic.happycodings.com/Files_Directories_Drives/code54.html

摘录

Function FileLoadToArray(ByRef asLines() As String, ByVal sFileName As String) As String
    Dim iFileNum As Long, lFileLen As Long
    Dim sBuffer As String

    'Initialise Variables
    On Error GoTo ErrFailed

    'Open File
    iFileNum = FreeFile
    Open sFileName For Binary Access Read As #iFileNum
    'Get the size of the file
    lFileLen = LOF(iFileNum)
    If lFileLen Then
        'Create output buffer
        sBuffer = String(lFileLen, " ")
        'Read contents of file
        Get iFileNum, 1, sBuffer
        'Split the file contents
        asLines = Split(sBuffer, vbNewLine)
    End If

    Close #iFileNum
    'Return success
    FileLoadToArray = ""

    Exit Function

ErrFailed:
    Debug.Assert False
    Debug.Print Err.Description
    FileLoadToArray = Err.Description
    'Close file
    If iFileNum Then
        Close #iFileNum
    End If
End Function

答案 1 :(得分:1)

我的VB6有点生疏,但我觉得它是这样的,感谢谷歌! :P

DIM FileNo AS Integer
DIM strNameList() AS STRING

FileNo = FreeFile
Open "file.dat" For Input As FileNo
Do Until EOF(FileNo)
   Line Input FileNo, strNameList(UBound(strNameList))
   REDIM Preserve strNameList(UBound(strNameList) + 1)
Loop
Close FileNo

现在strNameList将包含文件中的条目数组...... Phew ...我希望这是正确的,尽管我有质朴的技能....

答案 2 :(得分:0)

您可以使用通用的read-all-file功能

Private Function ReadFile(sFile As String) As String
    Dim nFile       As Integer

    nFile = FreeFile
    Open sFile For Input Access Read As #nFile
    ReadFile = Input$(LOF(nFile), nFile)
    Close #nFile
End Function

Split这样的功能

    Dim vSplit As Variant
    vSplit = Split(ReadFile("your_file.txt"), vbCrLf)