|
|
Title | Quickly copy UDT records from a file into an array |
Keywords | UDT, user-defined type, file |
Categories | Software Engineering, Files and Directories |
|
|
To load the data, open the file for Binary access specifying the file's entire size as the record length. Allocate an array big enough to hold all the data. Then use the Get statement to load all the data at once into the array.
|
|
Private Type BookType
Title As String * 50
URL As String * 50
ISBN As String * 13
Picture As String * 50
Pages As String * 4
Year As String * 4
End Type
Private m_NumBookData As Integer
Private m_BookData() As BookType
Private Sub Form_Load()
Dim buffer As BookType
Dim file_length As Long
Dim file_name As String
Dim fnum As Integer
Dim i As Integer
' Get the file name.
file_name = App.Path
If Right$(file_name, 1) <> "\" Then file_name = _
file_name & "\"
file_name = file_name & "Books.dat"
' Get the file's size and allocate room.
file_length = FileLen(file_name)
m_NumBookData = file_length / Len(buffer)
ReDim m_BookData(0 To m_NumBookData - 1)
' Load the book information.
fnum = FreeFile
Open file_name For Binary As fnum Len = file_length
Get #fnum, 1, m_BookData
Close fnum
' List the titles.
For i = 0 To m_NumBookData - 1
lstTitles.AddItem m_BookData(i).Title
' Save the index in the data array.
lstTitles.ItemData(lstTitles.NewIndex) = i
Next i
' Display the first record.
m_SelectedRecord = -1
lstTitles.ListIndex = 0
End Sub
|
|
To save the data, reverse these steps using the Put statement.
|
|
Private Sub Form_Unload(Cancel As Integer)
Dim file_name As String
Dim fnum As Integer
Dim buffer As BookType
Dim record_number As Integer
' Save the current record's data to the array
' in case the user just made changes.
SaveRecordToArray
' Get the file name.
file_name = App.Path
If Right$(file_name, 1) <> "\" Then file_name = _
file_name & "\"
file_name = file_name & "Books.dat"
' Open the file.
fnum = FreeFile
Open file_name For Binary As fnum Len = m_NumBookData * _
Len(buffer)
' Write out the array.
Put #fnum, 1, m_BookData
Close #fnum
End Sub
|
|
|
|
|
|