CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2001
    Posts
    8

    How do I Write the contents of a file to an array?

    I wish to have a .txt file containing string data and read that data one piece at a time to an array, (then perhaps edit the array but this bit I know how to do) then write the array back to the file. I dont mind how that data is kept in the .txt file.

    If anyone could show me the code on how to do this, I'd be very grateful.

    Thanks.


  2. #2
    Join Date
    Jul 2001
    Location
    Trivandrum, Kerala, India
    Posts
    21

    Re: How do I Write the contents of a file to an array?

    Hai,

    Here is the code


    option Explicit
    private astrColors() as string

    private Sub Command1_Click()
    Dim iArrayCount as Integer
    Dim j as Integer

    ' edit the next line to open your file
    Open "D:\colors.txt" for input as #1

    ' read line by line to array
    Do While Not EOF(1)
    ReDim Preserve astrColors(iArrayCount)
    Line input #1, astrColors(iArrayCount)
    iArrayCount = iArrayCount + 1
    Loop

    ' close the file
    Close #1

    ' just print the element in debug window
    for j = 0 to UBound(astrColors)
    Debug.print astrColors(j)
    next j

    End Sub

    private Sub Command2_Click()
    Dim i as Integer
    ' edit the next line to open your file
    Open "D:\colors.txt" for Output as #1

    ' loop through the array and write to file
    for i = 0 to UBound(astrColors)
    print #1, astrColors(i)
    next i

    ' close the file
    Close #1
    End Sub




    Place two command buttons in a form and paste the above code to the code window. This code shows how to read data from a text file in which each item is in a separate line. So, make sure in your file each item is separated by a line feed.

    All the best.

    Kishore.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured