Vous êtes sur la page 1sur 5

BINARY FILES

INTRODUCTION

As far as Visual Basic 6 is concerned, there are three modes in which a file can
be accessed.

Text Mode (Sequential Mode)


Binary Mode
Random Access Mode

In the Binary Mode, everything is written and retrieved as a Number. Hence, The
Number 17 will be stored as [17] in this mode and characters will be represented by their
ASCII Value as always.

DIFFERENCE BETWEEN BINARY MODE AND TEXT MODE

One major difference between Text Files and Binary Files is that Text Files
support Sequential Reading and Writing. This means that we cannot read or write
from a particular point in a file. The only way of doing this is to read through
all the other entries until you reach the point where you want to 'actually'
start reading. Binary Mode allows us to write and read anywhere in the file. For example we
can read data directly from the 56th Byte of the file, instead of reading all the
bytes one by one till we reach the 56th byte.

A file is a set of bytes/records stored together. Text Files are files which contain only
characters in ASCII or Unicode. Sequential Files are files opened in Sequential Mode.
Sequential Mode refers to any of the modes used for sequential file handling which are Input,
Output and Append. Binary Mode refers to the Binary Mode. Binary Files refer to files
opened in Binary Mode. Binary Files and Sequential Files are not different kinds of files but
rather different methods of accessing a file. Any file can be opened in both sequential and
binary modes (obviously not at the same time). If it is opened in sequential mode, it is only be
able to access data in the file sequentially. If it's opened in Binary mode, it is possible to
access any byte in the file without reading the previous bytes in the file.

1
BINARY FILE HANDLING

Private Sub Command1_Click()

Dim f As Long

f = FreeFile()

Open "c:\test.txt" For Binary As #f

Close #f

End Sub

As you can see, the FreeFile() function can also be used for binary files. The Open
Statement opens c:\test.txt in Binary Mode and the next statement closes the file. As obvious
as it may sound, you need to open a file before using it and close it when you have finished
reading or writing to it. Many programmers forget to add the Close statement which results in
the File Already Open Error, and it can be a pain to track down the exact location that caused
the error when you're dealing with many files. You should note that this snippet does more
than open and close a file. If the test.txt file is not present in C drive, then it creates a blank
file with the same name.

READING AND WRITING IN BINARY MODE

Here's an example which writes a string in a Binary File.

Private Sub Command1_Click()

Dim f As Long

f = FreeFile()

Open "C:\abc.txt" For Binary As #f

Put #f, , "This is the Test file."

Close #f

End Sub

2
The string "This is the Test file." is written to the abc.txt file in the C drive. The Put
Statement is used to write data to a binary file. The Syntax of Put is as follows:

Put #fileNumber, [startByte], varName

where

#fileNumber = A file handle ('f' is the file handle in the previous example)

startByte = (Optional) Byte position to start writing at.

varName = Variable/Literal whose contents are to be written. varName can be a


variable of any data type.

In the above example, we have skipped the second parameter which means that the
string is written at the current position of the file, which in this case is the beginning of the
file. We can choose to write data at a different position by specifying this parameter. Change
the Put Statement from the previous example to Put #f, 13, "B". Now run the program, quit
the program and open the abc.txt file. You will see that the file now contains "This is the Best
file." The Put statement in this case writes "B" at the 13th byte in the file. You can see that the
13th position in the file is the letter "T". Hence "T" gets replaced by "B". Unlike other
languages, VB6 does not store strings in ASCII format. The string "ABCD" is stored in VB6
like this:

[ 00 08 65 00 66 00 67 00 68 00 ]

The first two bytes contain the length of the following string. The latter portion of the
string uses 2 bytes for every character. Hence the trailing zeros for every character. That's
right, VB6 stores strings internally in Unicode but what I really want to tell you is that while
the length of this string is actually 10 bytes, when it is written in a File VB6 ALWAYS
STORES IT IN ASCII FORMAT. For more information on how the VB6 Len() function
works, click here to read my blog post which elucidates the working of the function. The Put
statement is used to write to a binary file. The Put statement is also used to write to Random
AccessFiles. A logical opposite of Put is Get, and that's what you'll need to use to read data
from a Binary File.

Private Sub Command1_Click()

Dim f As Long

3
Dim x As Byte

f = FreeFile()

Open "C:\abc.txt" For Binary As #f

Get #f, , x

Close #f

MsgBox x

End Sub

This will display 84 (ASCII Value of T) in a Message Box. The syntax of the Get
Statement is exactly the same as that of the Put statement. Experiment with the second
parameter and notice how you get ASCII values of the other elements. Let's try to read in the
first word of the file. We know that the first word is "This", so we'll create a Byte Array of
length 4 like this:

Private Sub Command1_Click()

Dim f As Long

Dim x(3) As Byte 'Creates Array from Index 0 to 3

Dim readresult As String

f = FreeFile()

Open "C:\abc.txt" For Binary As #f

Get #f, , x

Close #f

readresult = Chr(x(0)) & Chr(x(1)) & Chr(x(2)) & Chr(x(3))

MsgBox readresult

End Sub

4
Visual Basic will automatically fill in every element of the array x until it can't store
any more. So it starts from the first position (2nd parameter is not specified) and copies the
first 4 characters into the Byte Array x. Since the array x is of data type Byte, we need to
convert it to a string and then display it as shown.

CONCLUSION

In a sense, all files are "binary" in that they are just a collection of bytes stored in an
operating system construct called a file. However, when we talk about binary files, we are
really referring to the way VB opens and processes the file. The other file types (sequential
and random) have a definitive structure, and there are mechanisms built into the language to
read and write these files based on that structure. For example, the Input # statement reads a
sequential comma-delimited file field-by-field, the Line Input statement reads a sequential
file line by line, etc. On the other hand, it is necessary to process a file in binary mode when
that file does not have a simple line-based or record-based structure.

For example, an Excel "xls" file contains a series of complex data structures to
manage worksheets, formulas, charts, etc. If you really wanted to process an "xls" file at a
very low level, you could open the file in binary mode and move to certain byte locations
within the file to access data contained in the various internal data structures. Fortunately, in
the case of Excel, Microsoft provides us with the Excel object model, which makes it a
relatively simple matter to process xls files in VB applications. But the concept should be
clear: to process a file that does not contain simple line-oriented or record-oriented data, the
binary mode needs to be used and you must traverse or parse through the file to get at the
data that you need.

REFERENCES

http://msdn.microsoft.com/en-us/library/szz5syt3.aspx

http://www.dreamincode.net/forums/topic/56171-file-handling-in-visual-basic-6-part-2-
binary-file-handling/

http://www.vb6.us/tutorials/reading-and-writing-binary-files-visual-basic

Vous aimerez peut-être aussi