Open (statement)

<< Click to Display Table of Contents >>

Open (statement)

Open FileName [For Mode] [Access AccessMode] As [#]FileNumber

Opens a file for input/output operations.

FileName is the name of the file.

The optional parameter Mode can take one of the following values:

Mode

Description

Input

Sequential input. The file must already exist. AccessMode, if given, must be set to Read.

Output

Sequential output. The file is automatically created for output. If a file with the given name already exists, the file will be overwritten. AccessMode, if given, must be set to Write.

Append

Sequential output. Identical to Output, however the file pointer will be set to the end of the file, so that all following output commands append data to the existing file.

The optional parameter AccessMode restricts the type of access to the file:

AccessMode

Description

Read

Opens the file only for reading.

Write

Opens the file only for writing.

Read Write

Opens the file for reading and writing.

If the file does not exist, it will be automatically created, if either Append or Output mode was chosen; otherwise the Open command fails.

If the file is already opened by another process or the desired access mode is not possible, the Open command fails.

FileNumber is an integer value between 1 and 255 which identifies the file in the following access functions. The index of the next free file pointer can be returned using the FreeFile function.

See also: Close, FreeFile

Example:

Sub Main

 Open "TESTFILE" For Output As #1   ' Create file

 userData1$ = InputBox("Enter one text line.")

 userData2$ = InputBox("Enter one more text line.")

 Write #1, userData1, userData2     ' Write lile

 Close #1

 Open "TESTFILE" for Input As #2    ' Open file

 Print "File contents:"

 Do While Not EOF(2)

         Line Input #2, FileData        ' Read line

         Print FileData

 Loop

 Close #2                           ' Close file

 Kill "TESTFILE"                    ' Delete file

End Sub