* How to handle
files?
* Statements
related to file handling
* Functions related
to file handling
* File controls -
FileListBox, DirListBox and DriveListBox.
* Sample
application using file control and file related functions
A file is a collection of bytes stored on
the disk with a given name (called as filename). Every development tool
provides access to these files on the disk.
In this chapter we will understand how to access and manipulate files
using Visual Basic.
There are three special controls, called as
File controls, which deal with files and directories. We will also understand
how to use these controls in this chapter.
File handling
The following are three important steps in
handling a file.
¨
Opening the file
¨
Processing the file, i.e.
either reading the content of the file or writing the required data into file
or both.
¨
Closing the file
File access types
Depending upon the requirement you can use
any of the three different file access types:
Sequential
|
For reading
and writing text files in continuous blocks.
|
Random
|
For reading
and writing text or binary files structured as fixed-length records.
|
Binary
|
For reading
and writing arbitrarily structured files.
|
Opening the file using Open statement
A file is opened using OPEN statement in
Visual Basic. At the time of opening a file, you have to specify the following.
¨
Name of the file to be opened
¨
The mode in which file is to be opened. The mode specifies which
operations are allowed on the file.
¨
File number. Each open file contains a
file number. This file number is used to
access the file once the file is opened.
The file number must be unique.
Open pathname For mode [Access access]
[lock] As [#] filenumber [Len=reclength]
Option
|
Meaning
|
Pathname
|
Name of the
file to be opened.
|
Mode
|
Specifies the
mode in which file is to be opened. Valid modes: Append, Input, Output, Binary and Random. If
unspecified then Random is taken.
|
Access
|
Specifies the
operations that are permitted on the open file. Valid values: Read, Write, or ReadWrite.
|
Lock
|
Specifies the
operations restricted on the file opened by other users. Value values: Shared, Lock Read, Lock Write, and Lock Read Write.
|
Filenumber
|
A number in
the range 1 to 511. This number
must be unique among open files. Use FreeFile
function to obtain the next available number.
|
RecLength
|
Specifies the
size of each record in random files.
It should be <= 32767. For sequential files, this is the number of
characters buffered. This is ignored, if mode is Binary.
|
If the file is not existing then a new file
with the given name is created in Append, Binary, Output and Random modes.
Examples:
To
open TEST.TXT file in input mode:
Open “TEST.TXT” for input as #1
To
open NUMBER.DAT file in Binary mode:
Open “NUMBER.DAT” for binary access write as #1
To
open STUDENTS.DAT in random mode with a record length of 10:
Open
“STUDENTS.DAT” for random as #1 len = 10
To
get next available file number and then use it:
'FreeFile function returns the number that can
be used as the file 'number while opening the file
Fn = FreeFile
Open “TEST.TXT” for input as #fn
Functions related to files
The following are the functions that are
used with files.
Function
|
Meaning
|
Dir
|
Returns the
name of the file that matches the given name. If file is not existing then it
returns "" (null string).
|
FileLen
|
Returns the
length of the file in bytes.
|
LOF
|
Returns the
length of an open file in bytes.
|
EOF
|
Returns true,
if the specified file has reached end-of-file marker.
|
FreeFile
|
Returns the
next available file number.
|
Seek
|
Sets or
returns the position at which file pointer is currently positioned. For
random files it returns the number of records read or written so far.
|
Filecopy
|
Copies the
given source file to target file.
|
GetAttr
|
Returns the attributes
of the given path.
|
SetAttr
|
Changes the
attributes of the specified file to the given attributes.
|
FileDateTime
|
Returns the
date and time when file was last modified or created.
|
Loc
|
Returns the
current position of file pointer of an open file.
|
Table
10.1: Functions related to file handling.
Example:
To
find out the length of file CHARS.TXT:
fl = FileLen("c:\vb60\chars.txt")
To
find out whether file with the file number 1 has reached end-of-file:
if EOF(1) then
…
end if
To
check whether STUDENTS.DAT file is existing or not:
If
dir(“students.dat”) = “” then
MsgBox “File students.dat is
missing”
Else
Process
the file
End if
Statement related to file Input and output
The following statements are used to
perform input or output to file and other operations such as opening and
closing.
Statement |
Meaning |
Close
|
Closes an
open file
|
Get
|
Read a record
from the given position of the specified file.
|
Input( )
|
Returns the
specified number of characters from the given file.
|
Input #
|
Reads data
into specified list of variables from the given file.
|
Line Input #
|
Reads a
complete line from the given file.
|
Open
|
Opens the
given file in the specified mode.
|
Print #
|
Prints the
specified data to the given file.
|
Put
|
Writes a
record to the given position of the specified file.
|
Write #
|
Writes the
specified data to the given file.
|
Table
10.2: Statements related to file handling.
Not all statements are available in all
modes. So, the following table shows the availability of each statement in each
of the three access types.
In the table X denotes the availability of the command in the mode.
Statement |
Sequential
|
Random
|
Binary
|
Close
|
X
|
X
|
X
|
Get
|
|
X
|
X
|
Input( )
|
X
|
|
X
|
Input #
|
X
|
|
|
Line Input #
|
X
|
|
|
Open
|
X
|
X
|
X
|
Print #
|
X
|
|
|
Put
|
|
X
|
X
|
Write #
|
X
|
|
`
|
Table
10.3: The availability of the statements in three
access modes.
Note: See chapter 12, to understand how to use statements related to
sequential files. Detail discussion of Random and Binary files is beyond the
scope of this material. Please see on-line documentation if you are interested.
File Controls
Visual Basic provides a set of controls,
which are used to display files, directories and drives. These controls are
part of standard controls. The following are the file controls and what they do.
Control
|
Meaning
|
FileListBox
|
Displays a
list of files. This is a listbox that displays list of files from the path
specified using Path property.
|
DirListBox
|
Displays
hierarchical list of directories.
|
DriveListBox
|
Displays the
list of drives available in the system.
|
Table
10.4: File controls.
Properties and Events of FileListBox
The following are specific events and
properties of FileListBox.
Type
|
Name
|
Meaning
|
Property
|
Filename
|
Contains the
name of the file selected by user.
|
|
Path
|
Contains the
name of the directory from where list of files is taken.
|
|
Pattern
|
Specifies the
pattern that is used to filter filenames, such as *.exe.
|
|
System
|
Specifies
whether system files are to be displayed or not.
|
|
Readonly
|
Specifies
whether readonly files are to be displayed or not.
|
|
Hidden
|
Specifies
whether hidden files are to be displayed or not.
|
|
Archive
|
Specifies
whether archive files are to be displayed or not.
|
Event
|
Pathchange
|
Occurs
whenever path is changed.
|
|
Patternchange
|
Occurs
whenever pattern is changed.
|
Table
10.5: Properties and events that are specific to
FileListBox
Note: FileListBox also has properties that are available for listbox,
such as MultiSelect, ListCount etc., but it doesn’t have the
methods that are found with listbox, such as Additem.
Sample Application
Let us develop an application that used
file controls and file-related functions. This application allows user to
select a file from any directory and drive using three file-related controls
mentioned above. Once user selects a file, details of the selected file, such
as length, attributes and date of last modification will be displayed.
The following are the steps required to
create the sample application.
1.
Start a new project using File-> New Project and select Standard Exe as the project type.
2.
Place FileListBox, DirListBox
and DriveListBox on the left of the
form
3.
Place three label controls to
display messages File, Directories and Drives at the top of each of the
controls created in the previous step.
4.
Place a Frame control on the right of the form.
5.
Place a collection of label
controls. These label controls are used to display the information regarding
file.
6.
Also place a Listbox. This is used to display the
attributes of the file. A listbox is
selected because a file may contain more than one attribute, such as Readonly,
Hidden etc.
7.
Place a command button at the bottom. This is used to quit the application.
8.
Arrange all controls
Note: A frame is used only to
group controls physically to show that all the controls are related.
Changing properties
After having placed required controls on
the form, now let us concentrate on changing required properties to get
required appearance and functionality.
First let us concentrate on the properties
of file controls. For Directory list box and Drive list box no property needs to be
changed. But for File list box some
properties are to be changed in order to display all types of files. By default
only files of type Archive and Read-only
only will be displayed. But as we want to display all types of files, we have
to set Hidden and System properties
to True. Remember by default Archive and ReadOnly properties are already set to True.
The following table lists out the
properties to be changed for all other controls on the form.
Control
|
Property
|
Value
|
Frame1
|
Caption
|
Details
|
|
Fontbold
|
True
|
Label1
|
Caption
|
Files
|
Label2
|
Caption
|
Directories
|
Label3
|
Caption
|
Drives
|
Label4
|
Caption
|
Filename
|
Label5
|
Name
|
Lblname
|
|
Caption
|
“”
|
|
Borderstyle
|
1-Fixed
Single
|
Label6
|
Caption
|
Size
|
Label7
|
Name
|
Lblsize
|
|
Caption
|
“”
|
|
Borderstyle
|
1-Fixed
Single
|
Label8
|
Caption
|
Attributes
|
Label9
|
Caption
|
Last Updated
|
Label10
|
Name
|
Lbldate
|
|
Caption
|
“”
|
|
Borderstyle
|
1-Fixed Single
|
List1
|
Name
|
Lstattributes
|
Command1
|
Name
|
Cmdquit
|
|
Caption
|
&Quit
|
Note: The default names of the label control may not exactly match the
names of your label controls, if the order in which you created the label
control is different. change the properties.
Writing Code to connect file controls
At this stage, if you run the project and
select a different directory, it doesn’t change the list of files. But it
should. In the same way if you select a different drive, it doesn’t change the
list of directories. But again it should. So, we first concentrate on
connecting these three controls. That means when user changes the drive, then
automatically directory list box should display the list of directories from
new drive. The same is true with selecting a different directory in directory
list box (it should change list of files in file list box).
Whenever user changes the selection of
drive, Change event occurs for Drive list box. Take the drive selected
by user using Drive property of DriveListBox and set it to Path property of DirListBox. Then DirectoryListBox will get the list of directories
from new drive. Here is the code to do that.
Private
Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub
Listing
10.1: Code to connect drive list box with directory
listbox.
Whenever user select a different
directory, Change event for DirListBox
occurs. Take new path and assign that value to Path property of FileListBox
to get new list of file from newly selected directory. Here is the code to do
that.
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
Listing
10.2: Code to connect DirListBox to FileListBox.
Now let us get to crux. Whenever user
selects a file in FileListBox, we
have to display information regarding the selected file. The information is,
Full name of the file, Size of the file, Attributes of the file and Date and
time on which the file was last updated.
Getting size and date of last updation is
quite simple. It is just a matter of using FileLen
and FileDateTime functions.
Getting full filename is also done except
in one case. Path property of FileListBox contains the path in which
file is existing. Filename property
contains the name of the file. So to get complete filename we have to concatenate
these two values. As path is to be separated from filename using a backslash
(\), we also have to concatenate a backslash after path. However, when path is
referring to root directory, backslash is already there in the path. Adding an
extra backslash is going to make path invalid. So we have to see whether the
last character is a backslash. It can be done by taking the right most
character using Right function and
comparing it with backslash. Only when the rightmost character is not a
backslash we add backslash at the end of path. Listing 10.3, show the code to
do this.
Attributes of a file can be obtained using GetAttr function. But this function
returns an integer, which is to be decoded to get information regarding
attributes. The value returned by GetAttr
is to be bitwise Anded with predefined numbers to know the attributes of the
file. For example, to know whether file is readonly or not we have to use
bitwise And operator to perform bitwise Anded between the value returned by GetAttr and constant vbReadOnly.
We will write a procedure that takes the
attributes integer and a listbox. The procedure determines the attributes of
the file and adds items with attribute names to listbox. We name this procedure
as GetFileAttributes. Listing 10.4, show this procedure.
Private
Sub File1_Click()
Dim fn As String
'
form complete filename
fn =
File1.Path
‘ if
rightmost character is not backslash then add a backslash
If
Right(File1.Path, 1) <> "\" Then
fn = fn & "\"
End
If
fn =
fn & File1.FileName
lblname.Caption = fn
lblsize.Caption = FileLen(fn)
lbldate.Caption = FileDateTime(fn)
‘
call procedure to populate listbox with attributes of the file
GetFileAttributes GetAttr(fn), Lstattributes
End Sub
Listing
10.3: Code for click event of File control.
Public
Sub GetFileAttributes(attr As Integer, lstbox As ListBox)
‘clear all items from listbox
lstbox.Clear
‘check for read-only attribute
If
(attr And vbReadOnly) <> 0 Then
lstbox.AddItem "Read Only"
End
If
‘
check for Hidden attribute
If
(attr And vbHidden) <> 0 Then
lstbox.AddItem "Hidden"
End
If
‘check
for System attribute
If
(attr And vbSystem) <> 0 Then
lstbox.AddItem "System"
End
If
‘check
for Archive attribute
If
(attr And vbArchive) <> 0 Then
lstbox.AddItem "Archive"
End
If
End Sub
Listing 10.4: Code for
GetFileAttributes user-defined procedure
Also write code for Quit button, which
contains a single statement which is Unload
Me.
Test Run
Now run the project by pressing F5. First
you see list of files from current directory. Change directory by double
clicking on a new directory in the Dirlist box. This should change the list of
files. Also test whether a change in drive list box is changing the list of
directories.
If you select root directory and the select
IO.SYS
You can enhance the application by adding a
button to display the content of the selected file. However, for this you need
to take only text files (files that are readable) into account.