View contents of this chapter

Example - Random Files

The source code needed for this example is stored in the "Source Code\Chapter18\Random" directory.

'This procedure creates the file
Private Sub cmdCreate_Click()
    Dim intCounter As Integer
    Dim intFNum As Integer

    intFNum = FreeFile

    Open "C:\random.txt" For Random As #intFNum Len = 5

    For intCounter = 1 To 5
        ' record # same as data
        Put # intFNum, intCounter, intCounter
    Next intCounter

    Close # intFNum
End Sub

'This procedure changes a record
Private Sub cmdChange_Click()
    Dim intFNum As Integer

    intFNum = FreeFile

    Open "C:\random.txt" For Random As #intFNum Len = 5

    ' Write a new 2nd record
    Put # intFNum, 2, 10
    
    Close # intFNum
End Sub

Private Sub cmdRead_Click()
   Dim intCounter As Integer
   Dim intFNum As Integer
   Dim intVal As Integer

   intFNum = FreeFile

   Open App.Path & "\random.txt" For Random _
    As #intFNum Len = 5

   For intCounter = 1 To 5
      ' record # same as data
      Get #intFNum, intCounter, intVal
      MsgBox "Retrieved a " & intVal & " from Random.txt"
   Next intCounter

   Close #intFNum
End Sub

This example simply creates a file named Random, when a user clicks the cmdCreate button. When the user clicks the cmdChange button, the program changes a record value. The cmdRead button retrieves data from the file and shows in a message box.The above example uses the App object, which is a global object accessed with the App keyword. It determines or specifies information about the application's title, version information, the path and name of its executable file and Help files, and whether or not a previous instance of the application is running.

Play Sound

Today's lesson explained the fundamentals of file Input/Output. You learned how to read and write sequential and random files. These files are useful for storing text values.



© Universal Teacher Publications        INDEX Previous Screen Next Screen