
How-To... - Creating, Reading/Writing To/From files using the Open Statement
The
best thing about Visual Basics file-handling functions and statements is being
able to create a file and read/write to/from it. Most programs use this to
save data, program settings, registration information, etc. The syntax for
the Open Statement(out of the VB Help File) is as follows :-
Open pathname For
mode Access access lock As #filenumber Len= reclength
Not all parameters need to be passed. For example, Open "C:\Autoexec.bat" For Output As #1" would work fine. If the file you are trying to access does not exist and the mode is either 'Append', 'Output', 'Random', or 'Binary mode', then the file is automatically created. The following line of code would create a blank file on the root of the C:\ drive :-
Open "C:\VbHowTo.txt"
For Output As #1
Of course, the line above wouldn't work in Visual Basic, an important line of code is missing. Whenever you open a file, you MUST always close it. The line of code now looks like this :-
Open
"C:\VbHowTo.txt" For Output As #1
Close #1
There is three types of file access - Sequential, Random, and Binary Access.
Sequential Access, which is the Input, Output, and Append Modes, is most commonly used for writing text files, for example, an error log, or even just a Readme file.
Random Access, which is the Random Mode, is most commonly used when you wish to write and read data without closing the file. And because it is Random mode, the data is usually kept in record form so that it can be found easily.
Binary Access, which is the Binary Mode, is most commonly used when you want to store binary to a file, for example, storing a bitmap picture.
Because there is lots of things you can do with the Open statement, I have made up a Project file that will show you how you can use the Open Statement for the different modes.
You can download the fully-documented Project file from here.