How to do 'positioning' on a text file in read mode?

Posted on 2006-05-15
Last Modified: 2010-04-07
1. we can read a text file 'sequentially' , 1 line (1 record) at a time, with the following VB code:
   option explicit
   dim ch_read as integer    '  file pointer as my reading channel
   dim a_record as string    '  one line of the record for various length as string

   open "text_file.txt" for input as #file_nbr
   Line Input #ch_read, a_record
   ... so you read (Forward) a few line of this string into a_record

2. Questions:  how to 'rewind' the read N records, so I can read forward again?
    I used to see 'rewind N'  statment in some old basic or f77 language a while ago.
    there is a seek() statement in VB, but it only seeking through number of bytes
   from beginning, and I need to keep track it.  alghough this is not totally impossible
   (for example, the length of each record + 2 (LFCR), or somthing like this.)

3. I am looking for the 'rewind N' record statement in VB6
   also, can we do 'BOF'  --- positoin the next reading position at 'begging of the file'
   or  'EOF'   end of file, so we can do 'append' statement.

I hope someone can help me on this simple and useful mechanism to move around a 'file'
with one record at a time.  -- forward, and backward.



Question by:mshox1
    LVL 35

    Accepted Solution


    If you will need to 'move around' within the text file, I find it easiest to read the file into a string array, then navigate within the array easily.  It is quick to load, and much more versatile.  You can use a function like:

    Function GetTextFile(ByVal vFile As String) As String()
     Dim FileCont() As String, Cnt As Long, vFF As Long, tempStr As String
     ReDim FileCont(0)
     Open vFile For Input As #vFF
     Do Until EOF(vFF)
      Line Input #vFF, tempStr
      ReDim Preserve FileCont(Cnt)
      FileCont(Cnt) = tempStr
      Cnt = Cnt + 1
     Close #vFF
     GetTextFile = FileCont
    End Function

    To get the file into the array, then do whatever you need to with it.  Please don't hesitate to ask if you have any questions about it!
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    Here is a another way to get the lines of the file into an array:
    Private Sub Command1_Click()
        Dim lines() As String
        lines = Split(GetFileContents("c:\someFile.txt"), vbCrLf)
        Dim i As Integer
        For i = 0 To UBound(lines)
            Debug.Print lines(i)
        Next i
    End Sub

    Private Function GetFileContents(ByVal fileName As String) As String
        Dim ff As Integer
        Dim entireFile As String
        If Dir(fileName) <> "" Then
            ff = FreeFile
            Open fileName For Binary Access Read As #ff
            GetFileContents = Input(LOF(ff), ff)
            Close #ff
            MsgBox fileName, vbExclamation, "File Not Found"
        End If
    End Function
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    Unfortunately you can't use the Seek() method unless you open the file in Binary or Random modes.  In those modes you can only use the Get and Put methods to access the file and can no longer read it line by line with Line Input.
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    If you make your file fixed width, that is each line is a prefedined length, and lines cannot be longer than that (and shorter lines will be padded with spaces to fit) then you can open the file in Random mode and move back and forth between records in either direction or even jump to a specific record in the file.

    Here are some PAQs dealing with Random Access Files:
    LVL 20

    Expert Comment

    Here's another way.....

    Open the text file as a random access (fixed length) with a record size of 1.   Loop through and GET each character.  Concatenate he string until you reach the line delimiter (carriage return or line feed).

    You can track the starting byte of each line - then simply jump back to the line of your choice and review.

    Create a module and place this code.

    Type x
    s As String * 1
    End Type
    Public FS As x

    Create a button on a form and place this code:

    Private Sub Command0_Click()

    '------ 100000 = number of possible TEXT LINES in text file -----
    Dim vStartLine(1 To 100000) As Long
    Dim vRecCount As Long
    Dim vString As String

    Dim f As Long
    f = FreeFile
    Dim vFTot As Long

    Open "c:\YourTextFile.txt" For Random As #f Len = Len(FS)
    vFTot = LOF(f) / Len(FS)

    Dim j As Long

    vRecCount = 1
    vStartLine(vRecCount) = 1

    For j = 1 To vFTot
        Get #f, j, FS
        '---------- look for line delimiter (carriage return = chr(13) - Line Feed = chr(10) --------
        If FS.s <> Chr(13) And FS.s <> Chr(10) Then
            '---- concatenate string --------
            vString = vString & FS.s
            '-- only count logical recs if string is greater than 1 character (could be a 'blank' line)----
            If Len(vString) > 1 Then
                '---- do something with the string ---

                '--- depending on logic - reset j to equal vStartLine(WhateverRecValueYouWish) and go back through--
                '---- for instance.....
                '---- if Left(vstring,1) = "@" then J = vStartLine(vRecValue-1) --- go back 1 logical line ----
                '--- these are examples of vStartLine() -----
                '--- vStartLine(1) = 1
                '--- vStartLine(2) = 99
                '--- vStartLine(3) = 200

                '---- clear the string for next logical line ---
                '--- don't add recs if reviewing data (if 'rewinding') ----
                If j > vStartLine(vRecCount) Then
                    vRecCount = vRecCount + 1
                    vStartLine(vRecCount) = j
                End If
            End If
            vString = ""
        End If

    Next j


    Scott C.

    End Sub

    LVL 20

    Expert Comment

    After thinking about this for a moment.... this line should probably be

                '---- clear the string for next logical line ---
                '--- don't add recs if reviewing data (if 'rewinding') ----
                If j > vStartLine(vRecCount) Then
                    vRecCount = vRecCount + 1

                   '--- since the character of J is the line delimiter - vStartLine(vReccount) should be J + 1 ( which would be the
                   '--- next byte ----
                    vStartLine(vRecCount) = j + 1

                End If

    Scott C.

    Author Comment

    Thank you everyone for your great input.

    I think my really question is if VB have the 'rewind nbr_of_records' capability,
    (for variable length record)

    Obviously there is non.  
    I do know how to deal this with loading the file into dynamic array, or treat as random access
    (fixed length) ... and understand different 'side affect' have and need to be address.  I thank you
    everyone's input.

    I would like to 'close' this discussion chapter on this subject.



    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
    You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
    Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
    This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now