Module Module1
'random files don't work as normal files
'random files can ONLY store information as the record type
'Employee record will be used to format the information as records to store
in the file
Structure Employee
'Note: As opposed to other primitive data types,
' String is the only one that has a variable size
' that is, it doesn't have a fixed size
'For random files, EVERY record MUST have the SAME size
'So, we NEED to specify the size of the String used
<VBFixedString(20)> Dim name As String '20 bytes
Dim age As Integer '4 bytes
Dim salaray As Double '8 bytes
Dim isMarried As Boolean '1 byte
'Total = 20 + 4 + 8 + 1 = 33 bytes
End Structure
Sub assignInitialRecords(emp As Employee, fileNum As Integer)
'Record 1
emp.name = "Oumeira"
emp.age = 69
emp.salaray = 420000
emp.isMarried = False
FilePut(fileNum, emp, 1) 'storing record emp at Record 1
'We can overwrite over the same emp record
'as the first one is already saved in the file
'Record 2
emp.name = "AliKa"
emp.age = 13
emp.salaray = 15999.99
emp.isMarried = True
FilePut(fileNum, emp, 2) 'storing record emp at Record 2
'Case Scenario: AliKa was fired and Rushil was hired to replace her
'Note: Compared to sequential files, we can directly update(overwrite)
the file
' without creating a new file
emp.name = "Rushil"
emp.age = 30
emp.salaray = 20000
FilePut(fileNum, emp, 2) 'updating record 2
End Sub
Function readRecord(emp As Employee, fileNum As Integer)
'reads record 1 and stores it in emp
FileGet(fileNum, emp, 1)
Return emp
End Function
Sub displayRecordSize(emp As Employee)
Console.WriteLine(Len(emp))
'Expected: 33 bytes, Ouput: 34 bytes
'Explanation: Computers work better with even numbers (binary registers)
'so, the compiler uses 34 bytes instead of 33 bytes for faster access
'Read more on "Padding" if interested
'(precise Padding for random files, otherwise might get unexpected
results)
End Sub
Function getIndex(line As String)
'prier hash pas sorti
End Function
Sub Main()
Dim fileName As String = "employees.dat"
'creating a record of type Employee to manipulate the records
Dim emp As Employee
'fileNum is used as a "nickname" for the file
'The name of the random file is only used ONCE when opening it
'The rest of the time, fileNum is used to represent the file
'Don't ask why, I didn't make the rules
Dim fileNum As Integer = 1
' Nickname, fileName, random mode, skipping 2 unneeded
arguments, FIXED length of employee record
FileOpen(fileNum, fileName, OpenMode.Random, ,
, Len(emp))
assignInitialRecords(emp, fileNum)
emp = readRecord(emp, fileNum)
'Display the record
'Note: Since we used a fixed-size string, it will have trailing empty
spaces at the end
'The trim functon is used to remove the empty spaces
Console.WriteLine("Employee 1: " & Trim(emp.name) & ", " & emp.age & ", "
& emp.salaray & ", " & emp.isMarried)
'close file
FileClose(fileNum)
Console.WriteLine("Done")
Console.ReadLine()
End Sub
End Module