Home / lang / open 
OPEN
Syntax
hStream = OPEN sFileName FOR [ READ | INPUT ] [ WRITE | OUTPUT ] [ CREATE | APPEND ] [ WATCH ]

Opens a file for reading, writing, creating or appending data. The file must exist, unless the CREATE keyword is specified.

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

By default, streams are buffered.

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

Unlike other Basic dialects, Gambas will never delete a file when it is opened by the WRITE keyword for instance.  So if the new contents 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
MessageDescription
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 did not exist yet and write access to the parent directory is not allowed.
File is a directory (#46) File name refers to a directory.
File or directory does not exist (#45) File name 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) File name was to be created but the device containing File name has no room for the new file.
Not a directory (#49) A component used as a directory in File name is not, in fact, a directory.
System error... (#42) Other possible system errors:
  • Too many symbolic links were encountered in resolving File name.
  • The process already has the maximum number of files open.
  • The system limit on the total number of open files has been reached.
  • File name 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.
  • File name refers to a file on a read-only filesystem and write access was requested.
  • File name refers to an executable image which is currently being executed and write access was requested.

Example
' 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
Example
' 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
Example
' 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
Stream & Input/Output functions  File & Directory Functions  Stream