File I/O in Visual Basic

2 types of files exist:

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

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 = false
configfound = false
crlf = chr$(13) + chr$(10)
end sub

 

sub btnOpen_click()
dim cline as string
if configfound then
beep
exit sub
end if
open "c:\config.sys" for input as #1
do while not EOF(1)
line input #1, cline
txtContent.text = txtContent.text + cline + crlf
loop
close #1
configfound = TRUE
end sub

 

sub btnSave_click()
If not (configfound AND textchanged) then
beep
exit sub
end if
open "c:\config.sys" for output as #1
print #1, txtContent.text
close #1
end sub

 

sub btnQuit_click()
end
end sub

 

sub txtContent_change()
textchanged = TRUE
end 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 var’s

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

...

..

...

...

...