Gambas Documentation
Application Repository
Code Snippets
Compilation & Installation
Components
Controls pictures
Deprecated components
Developer Documentation
Development Environment Documentation
Documents
Error Messages
Gambas Playground
How To's
Language Index
#Else
#Endif
#If
+INF
-INF
Abs
Access
ACos
ACosh
Alloc
AND
AND IF
Ang
APPEND
Arithmetic Operators
Array Declaration
AS
Asc
ASin
ASinh
Asl
Asr
ASSERT
Assignment Operators
Assignments
ATan
ATan2
ATanh
Base$
Base64$
BChg
BClr
BEGINS
Bin$
Binary Data Representation
Bool@
Boolean@
BREAK
BSet
BTst
BYREF
Byte@
CASE
CATCH
CBool
Cbr
CByte
CDate
Ceil
CFloat
CHGRP
CHMOD
Choose
CHOWN
Chr$
CInt
CInteger
CLASS
CLong
CLOSE
Comp
Comparison methods
Complex numbers
CONST
Constant Declaration
Constant Expression
CONTINUE
Conv$
Conversion Functions
COPY
Cos
Cosh
CPointer
CREATE
CREATE PRIVATE
CREATE STATIC
CShort
CSingle
CStr
CString
CVariant
Datatypes
Date
Date@
DateAdd
DateDiff
Day
DConv$
DEBUG
DEC
Dec
DEFAULT
Deg
DFree
DIM
Dir
DIV
DO
DOWNTO
EACH
ELSE
END
ENDIF
ENDS
END SELECT
END STRUCT
END WITH
ENUM
Enumeration declaration
Eof
ERROR
ERROR TO
Eval
Even
EVENT
Event Loop
Events declaration
EXEC
Exist
Exp
Exp2
Exp10
Expm
EXPORT
EXTERN
External Function Declaration
External Function Management
FALSE
FAST
FAST UNSAFE
File & Directory Paths
FINALLY
Fix
Float@
Floor
FLUSH
FOR
FOR EACH
Format$
Frac
Free
FromBase
FromBase64$
FromUrl$
FUNCTION
Global Special Event Handlers
GOSUB
GOTO
Hex$
Hour
Html$
Hyp
IF
IIf
IN
INC
INCLUDE or #INCLUDE
INHERITS
Inline Arrays
Inline Collections
INPUT
INPUT FROM
InStr
Int
Int@
Integer@
IS
IsAlnum
IsAscii
IsBlank
IsBoolean
IsDate
IsDigit
IsDir
IsFloat
IsHexa
IsInf
IsInteger
IsLCase
IsLetter
IsLong
IsLower
IsMissing
IsNaN
IsNull
IsNumber
IsPunct
IsSpace
IsUCase
IsUpper
KILL
Labels
Language Constants
LAST
LCase$
Left$
Len
LET
LIBRARY
LIKE
LINE INPUT
LINK
Localization and Translation Functions
Local Variable Declaration
LOCK
Lof
Log
Log2
Log10
Logical Operators
Logp
Long@
LOOP
Lsl
Lsr
LTrim$
Mag
MATCH
Max
ME
Method Declaration
Mid$
Min
Minute
MkBool$
MkBoolean$
MkByte$
MkDate$
MKDIR
MkFloat$
MkInt$
MkInteger$
MkLong$
MkPointer$
MkShort$
MkSingle$
MOD
Month
MOVE
NEW
NEXT
NOT
Now
NULL
Oct$
Odd
ON GOSUB
ON GOTO
OPEN
OPEN MEMORY
OPEN MEMORY
OPEN NULL
OPEN PIPE
OPEN PIPE
OPEN STRING
Operator Evaluation Order
OPTIONAL
OR
OR IF
OUTPUT
OUTPUT TO
PEEK
Pi
Pointer@
PRINT
PRIVATE
PROCEDURE
PROPERTY
Property Declaration
PUBLIC
QUIT
Quote$
Rad
RAISE
Rand
RANDOMIZE
RDir
READ
Realloc
REPEAT
Replace$
RETURN
Right$
RInStr
RMDIR
Rnd
Rol
Ror
Round
RTrim$
Scan
SConv$
Second
SEEK
Seek
SELECT
Sgn
SHELL
Shell$
Shl
Short@
Shr
Sin
Single@
Sinh
SizeOf
SLEEP
Space$
Special Methods
Split
Sqr
Stat
STATIC
STEP
STOP
STOP EVENT
Str$
Str@
String$
String@
String Operators
StrPtr
STRUCT
Structure declaration
SUB
Subst$
SUPER
SWAP
Swap$
Tan
Tanh
Temp$
THEN
Time
Timer
TO
Tr$
Trim$
TRUE
TRY
TypeOf
UCase$
UnBase64$
UNLOCK
UnQuote$
UNTIL
Url$
USE
User-defined formats
Using reserved keywords as identifiers
Val
Variable Declaration
VarPtr
WAIT
WATCH
Week
WeekDay
WEND
WHILE
WITH
WRITE
XOR
Year
Language Overviews
Last Changes
Lexicon
README
Search the wiki
To Do
Topics
Tutorials
Wiki License
Wiki Manual

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 CREATE keyword is specified, then the file is created, or cleared if it already exists.

  • If the APPEND keyword is specified, then the file pointer is moved to the end of file just after the file is opened.

  • If the READ or WRITE keywords are specified, then the input and output are not buffered.

  • If the INPUT or OUTPUT keywords are specified, then the input and output are buffered.

  • If the WATCH keyword is specified, the file is watched by the interpreter via the select(2) system call :
    • If at least one byte can be read from the file, then the event handler File_Read() is called.

    • If at least one byte can be written into the file, then the event handler File_Write() is called.

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

  iByte = READ #hFile As Byte
  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
...
iData = READ #hFile As Integer

See also