Professional Documents
Culture Documents
Binary and Random-Access Files
Binary and Random-Access Files
Binary and
Random-Access Files
hapter 9 introduced sequential file operations. The files you worked with in that
chapter were text files, which means that data is stored in the files as text. Even
the numbers that you store in a text file are converted to text. When you read an item
from a text file, it is read as a string. Sometimes text files are convenient to work with
because you can open them in programs such as Notepad.
Visual Basic also lets you create binary files. Data stored in a binary file is stored in its
raw binary format. Binary files are sometimes smaller than text files, and the data that is
read from them does not have to be converted before math or other operations are performed on them. Although you might be able to open a binary file in Notepad, you cannot read its contents because the file is not formatted as text.
To open a binary file, first you create a FileStream object, and then you create a
BinaryWriter or BinaryReader object. For example, the following code creates a new
binary file named myfile.dat. A BinaryWriter object can then be used to write binary
data to the file.
Dim outputFile As System.IO.BinaryWriter
Dim fs As System.IO.FileStream
fs = System.IO.File.Open("myfile.dat", System.IO.FileMode.Create)
outputFile = New System.IO.BinaryWriter(fs)
The System.IO.File.Open method in this code takes two arguments. The first
argument is the pathname of the file. The second argument specifies the mode
in which the file will be opened. Valid modes are FileMode.Append, FileModeCreate,
FileMode.CreateNew,
FileMode.Open,
FileMode.OpenOrCreate,
and
FileMode.Truncate. You can view detailed descriptions of each of these modes by
searching for FileMode Enumeration in the Visual Basic Help system. To avoid having to
repeat the System.IO namespace before each FileMode, use the following Imports
statement: Imports System.IO
F-1
F-2
Appendix F
The BinaryWriter class has a Write method that writes data in binary form to a file.
The following code shows how an integer is written to a file. Assume that age is an
integer variable.
age = CInt(InputBox("Enter your age."))
outputFile.Write(age)
To close a binary file, use the Close method, as shown in the following statement:
outputFile.Close()
Reading data from a binary file is also straightforward. The following code shows how
a binary file may be opened, an integer value read from it, and then closed.
Dim inputFile As System.IO.BinaryReader
Dim fs As System.IO.FileStream
Dim age As Integer
fs = System.IO.File.Open("myfile.dat", SystemIO.FileMode.Open)
inputFile = New System.IO.BinaryReader(fs)
age = inputFile.ReadInt32()
inputFile.Close()
Table F-1 lists some of the BinaryReader methods for reading data from a file.
Table F-1 Some of the BinaryReader methods for reading data
Method
Description
PeekChar
Reads the next available item as a character from the file and
does not advance the read position. Returns 1 if there are no
more items in the file.
Read
Reads the next character from the file and advances the read
position to the next item in the file.
ReadBoolean
Reads a Boolean value from the file and advances the read
position to the next item in the file.
ReadByte
Reads a Byte value from the file and advances the read position
to the next item in the file.
ReadBytes
Reads an array of Byte values from the file and advances the read
position to the next item in the file.
ReadChar
Reads a Char value from the file and advances the read position
to the next item in the file.
ReadChars
Reads an array of Char values from the file and advances the
read position to the next item in the file.
ReadDecimal
Reads a Decimal value from the file and advances the read
position to the next item in the file.
ReadDouble
Reads a Double value from the file and advances the read
position to the next item in the file.
ReadInt16
Reads a Short value from the file and advances the read position
to the next item in the file.
ReadInt32
Reads an Integer value from the file and advances the read
position to the next item in the file.
ReadInt64
Reads a Long value from the file and advances the read position
to the next item in the file.
ReadSingle
Reads a Single value from the file and advances the read position
to the next item in the file.
Appendix F
Random-Access Files
Random-access files provide an efficient way to store and retrieve data so that records
may be modified selectively. Sequential files may only be processed in sequential order,
hence the name sequential. Processing begins at the first item and continues in sequence
to the last item, unless the process is halted and the file closed. A random-access file, on
the other hand, does not have to be processed in sequence. You can select any item in the
file, read it, and modify it in place.
A problem arises when you store strings in a random-access file because strings are variable lengths. To declare a string with a fixed length, prefix its declaration with the following attribute.
<VBFixedString(Length)>
Length is the fixed length of the string. The following structure declaration uses this
attribute and it is suitable for holding data that will be written to a random-access file.
Structure PersonData
<VBFixedString(25)> Public Name As String
Public Age As Integer
<VBFixedString(25)> Public Address As String
<VBFixedString(15)> Public City As String
<VBFixedString(2)> Public State As String
<VBFixedString(10)> Public PostalCode As String
<VBFixedString(15)> Public Telephone as String
End Structure
F-3
F-4
Appendix F
FileNumber is an integer that you use to identify the file. FileName is the name of the
file, which can include the files path. AccessMode specifies how the file will be accessed,
and can be one of these values: OpenAccess.Default, OpenAccess.Read,
OpenAccess.ReadWrite, or OpenAccess.Write. Note that a random-access file can be
opened for both reading and writing with OpenAccess.ReadWrite. RecordLength is
the size of the records that will be stored in the file.
You can determine the size of a record with the Len function. The general format is
Len(Object)
Object is any variable or object. The function returns the size of Object.
For example, the following code declares person as a PersonData structure variable. It
passes person to a Sub procedure, GetData, which stores data in person. Then it opens
a random-access file named CustomerData.dat. The Len function is used to determine
the length of the person variable.
Dim person As PersonData
GetData(person)
FileOpen(1, "CustomerData.dat", OpenMode.Random, _
OpenAccess.ReadWrite, OpenShare.Default, Len(person))
Appendix F
each record from a file into the person variable, and passes person to a function named
DisplayData.
recNum = 1
Do Until EOF(1)
FileGet(1, person, recNum)
DisplayData(person)
recNum += 1
Loop
F-5