lang • open

OPEN

Stream = OPEN FileName [ FOR [ READ | INPUT ] [ WRITE | OUTPUT ] [ CREATE | APPEND ] [ WATCH ] ]

Opens a file for reading, writing, creating, or appending data. The file must exist, or the CREATE keyword must be used.

If the file is successfully opened, a stream object is returned to the variable Stream.

By default, streams are buffered.

If you want to have an unbuffered stream, you must use the READ or WRITE keyword explicitly.

Unlike other Basic dialects, Gambas will never delete the contents of a file when it is opened by the WRITE keyword. So, if the new content is smaller than the old one, some garbage of the old file version will remain at the end of the new file. To avoid this, open the file including the CREATE keyword.

Errors

Message

Description
Access forbidden (43) The requested access to the file is not allowed, or search permission is denied for one of the directories in the path prefix of pathname, or the file does not exist yet and write access to the parent directory is not allowed.
File is a directory (46) FileName refers to a directory. Use the function Dir instead!
File or directory does not exist (45) FileName does not exist, or a directory component in pathname does not exist or is a dangling symbolic link.
Out of memory (1) The system ran out of memory.
Device is full (37) FileName was to be created but the device containing FileName has no room for the new file.
Not a directory (49) A component used as a directory in FileName is not, in fact, a directory.
System error... (42) Other possible system errors:
  • Too many symbolic links were encountered in resolving FileName.

  • The process already has the maximum number of files open.

  • The system limit on the total number of open files has been reached.

  • FileName refers to a device special file and no corresponding device exists.

  • The named file is a named pipe and no process has the file open for reading.

  • FileName refers to a file on a read-only filesystem and write access was requested.

  • FileName refers to an executable image which is currently being executed and write access was requested.

Examples

' Prints the contents of a text file to the screen
    
Dim hFile As File
Dim sLine As String
    
hFile = Open "/etc/passwd" For Input
    
While Not Eof(hFile)
  Line Input #hFile, sLine
  Print sLine
Wend

' Watching a serial port

Dim hFile As File

hFile = Open "/dev/ttyS0" For Read Write Watch

...

Public Sub File_Read()

  Dim iByte As Byte

  Read #hFile, iByte
  Print "Got one byte: "; iByte

End

' Reading data from a BMP file, known to use little-endian format :

Dim hFile As File
Dim iData As Integer

hFile = Open "image.bmp" For Input
hFile.ByteOrder = gb.LittleEndian
...
Read #hFile, iData

See also