-
Notifications
You must be signed in to change notification settings - Fork 2
/
fileio.scm
97 lines (80 loc) · 2.8 KB
/
fileio.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
;;; File input/output utilities
;; Copyright (C) 2004 Brailcom, o.p.s.
;; Author: Milan Zamazal <pdm@brailcom.org>
;; COPYRIGHT NOTICE
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
;; for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
(require 'util)
(defmac (with-open-file form)
(let* ((spec (nth 1 form))
(body (nth_cdr 2 form))
(var (nth 0 spec))
(filename (nth 1 spec))
(how (or (nth 2 spec) "r")))
`(let ((,var (fopen ,filename ,how)))
(unwind-protect* (begin ,@body)
(fclose ,var)))))
(defmac (with-temp-file-data form)
(let* ((spec (nth 1 form))
(body (nth_cdr 2 form))
(filename (nth 0 spec))
(data (nth 1 spec)))
`(with-temp-file ,filename
(write-file ,filename ,data)
,@body)))
(define (write-file filename string)
(with-open-file (f filename "w")
(fwrite (if (symbol? string) (format nil "%s" string) string) f)))
(define (read-file filename)
(with-open-file (f filename)
(let* ((strings '())
(buffer (format nil "%1024s" ""))
(buflen (length buffer))
(n 0)
(reading t))
(while reading
(set! n (fread buffer f))
(if n
(begin
(push (substring buffer 0 n) strings)
(when (< n buflen)
(set! reading nil)))
(set! reading nil)))
(apply string-append (reverse strings)))))
(define (make-read-line-state)
(list ""))
(define (read-line file state)
(let* ((text (car state))
(line (and text (string-before text "\n"))))
(cond
((not text)
nil)
((equal? line "")
(let* ((buffer (format nil "%256s" ""))
(n (fread buffer file)))
(cond
((and (not n) (eqv? text ""))
(set! line nil)
(set! text nil))
((not n)
(set! line text)
(set! text nil))
(t
(set! text (string-append text (substring buffer 0 n)))
(let ((state* (list text)))
(set! line (read-line file state*))
(set! text (car state*)))))))
(t
(set! text (string-after text "\n"))))
(set-car! state text)
line))
(provide 'fileio)