File I/O in Visual Basic
2 types of files exist:
- sequential plain text; read and write 1 line at a time
- random access read/write in any order; lines(records) must all be equal length
File Operations
Normally, use the common dialog control to present to present the file open or file save as dialog box.
You can customize using
- file list box
- directory list box
- drive list box
Sequential Files
@ |
e |
c |
h |
o |
o |
f |
f |
<CR> |
<LF> |
s |
e |
t |
Bytes stored in file on disk
Displayed on screen:
@echo off
set ...
Carriage Return = ASCII 13
Line Feed = ASCII 10
Opening & Closing Sequential Files
OPENING A FILE ...
open "c:\config.sys" for input as #1
or
doc$ = "c:\config.sys"
open doc$ for input as #1
Because OPEN for OUTPUT destroys existing files ...
if dir$("c:\config.sys") <> "" then
if inputbox("c:\config.sys already exists. Delete?")<> "Yes" then
exit sub
end if
end if
open "c:\config.sys" for output as #2
CLOSING A FILE
close #1
Reading from a Sequential File
LINE INPUT #fileNumber,stringvariable
open filevar for input as #1
do while not EOF(1)
line input #1, linevar
/* do stuff */
loop
close #1
Writing to a Sequential File
PRINT #fileNumber, expression | expression | ...
If semicolons are used to separate expressions THEN no space is between record fields
If commas are used to separate expressions THEN skip to next print field (up to 14 chars)
Example using Sequential Files: Program to edit config.sys
3 command buttons:
Multiline text box with both scrollbars; txtContent
General declarations:
The procedures:
sub form_load()textchanged = falseconfigfound = falsecrlf = chr$(13) + chr$(10)end sub
sub btnOpen_click()dim cline as stringif configfound thenbeepexit subend ifopen "c:\config.sys" for input as #1do while not EOF(1)line input #1, clinetxtContent.text = txtContent.text + cline + crlfloopclose #1configfound = TRUEend sub
sub btnSave_click()If not (configfound AND textchanged) thenbeepexit subend ifopen "c:\config.sys" for output as #1print #1, txtContent.textclose #1end sub
sub btnQuit_click()endend sub
sub txtContent_change()textchanged = TRUEend sub
Random Access Files
open filename for random as filenumber len = recordlength
type Weasel
name as string * 32
color as string * 12
weight as integer
length as integer
birthdate as double
end type
Fix size of string vars
Sum up record length: 32 + 12 + 2 + 2 + 8 = 56
Reading & Writing to Random Access Files
record # |
name |
color |
weight |
length |
birthdate |
1 |
sigmund |
red |
18 |
11 |
04/05/94 |
2 |
sigfried |
brown |
14 |
10 |
03/15/93 |
3 |
... |
.. |
... |
... |
... |