Blitz3D+ Command Reference

OpenFile ( filename$ )

Parameters

filename$ - path and name of the file to open

Description

Opens an existing file for both reading and writing.

Returns a file stream handle to pass to the Read/Write commands, or 0 if the file could not be opened. The file must already exist - OpenFile never creates one, that is WriteFile's job.

Reading and writing share one position in the file, which starts at the first byte and is moved with SeekFile. That makes OpenFile the command for updating a file in place: jump to a record, rewrite it, leave the rest untouched - the classic pattern for a slot-based save file or a simple database.

Take extra care when the file contains strings written with WriteString: strings are not a fixed size, so overwriting one with a longer one tramples the data after it. Fixed-size records (ints, floats, padded strings) are much easier to update safely.

Close the file with CloseFile when you are done.

See also: ReadFile, WriteFile, CloseFile, SeekFile, FilePos.

Example

; OpenFile Example
; ----------------

; Create a small save-game file first (OpenFile cannot create files)
file=WriteFile("demo_savegame.dat")
WriteInt file,100
WriteInt file,3
CloseFile file
Print "Created demo_savegame.dat with gold=100, lives=3"

; OpenFile opens an EXISTING file for both reading and writing
file=OpenFile("demo_savegame.dat")

; Jump to the second integer (offset 4) and update it in place
SeekFile file,4
WriteInt file,5
Print "Updated lives to 5 in place - no need to rewrite the whole file"

; Seek back to the start and read both values back
SeekFile file,0
Print "Gold : "+ReadInt(file)
Print "Lives: "+ReadInt(file)

CloseFile file

; Clean up the demo file
DeleteFile "demo_savegame.dat"
Print "Deleted demo_savegame.dat"

Print ""
Print "Press any key to close the example"
WaitKey

End

Index