5.7 Files - naver/lispe GitHub Wiki

Files

back

; File methods

(file (path (mode (quote r))) Open a file with 'pathname' and action == 'r|'w|'a)
(file_close (stream) Close a file)
(file_read (stream (nb -1)) Read the whole file at once or nb characters)
(file_readline (stream) Read one line from the file)
(file_readlist (stream) Read the whole file and store each line in a list)
(file_getchar (stream) Read one UTF8 character at a time)
(file_getstruct (stream o c) Read an embedded structure in the file that starts at openning character 'o' and stops at closing character 'c'). It returns 'nil' when no more structure has been found.
(file_write (stream str) Write a string to a file)
(file_seek (stream nb (offset 0)) Positions the head at nb. offset are: 0 (from beginning), 1 (from current position) or 2 (end))
(file_tell (stream) Returns the current position in the stream)
(file_eof (stream) Check if a file reached 'end of file')

Note on: file_getstruct

file_getstruct is used to read successive structures from a file, which starts with a specific character and ends with another.

(file_getstruct stream "{" "}")

The file can contain sub-structures of the same sort, which means that the method will only stop when all sub-structures have been consumed.

Hence, file_getstruct can return: {{a:b} {c:d}}.

This method can be called as many times as necessary to read all balanced structures. When the last structure has been read, the system returns nil.

Important: file_getstruct returns a string object. If this string matches some LispE structures such as lists or dictionaries, you can use json_parse to transform it into actual LispE containers.

Examples

; Files
; We open a file for reading
(setq r (file "myfile.txt" 'r))

; We read one line
(println (file_getline r))

; we close our file
(file_close r)

; We write in a file
(setq w (file "myfile.txt" 'w))
(file_write w "my test")
(file_close w)

; We read dictionaries from a JSON file.
;Important d is always a string
; We uses json_parse to transform them into actual structures
(setq j (file "myfile.json" 'r))
(setq d (file_getstruct j "{" "}"))
(while d
   (println (json_parse d))
   (setq d (file_getstruct j "{" "}"))
)

(file_close j)