Indent with 4 spaces
[pforth] / fth / file.fth
CommitLineData
593eb738
HE
1\ READ-LINE and WRITE-LINE
2\
3\ This file is in the public domain.
4\
5
6private{
7
810 constant \n
913 constant \r
10
11\ Unread one char from file FILEID.
12: UNREAD ( fileid -- ior )
13 { f }
14 f file-position ( ud ior )
15 ?dup
16 IF nip nip \ IO error
17 ELSE 1 s>d d- f reposition-file
18 THEN
19;
20
21\ Read the next available char from file FILEID and if it is a \n then
22\ skip it; otherwise unread it. IOR is non-zero if an error occured.
23\ C-ADDR is a buffer that can hold at least on char.
24: SKIP-\n ( c-addr fileid -- ior )
aad4537d
HE
25 { a f }
26 a 1 f read-file ( u ior )
27 ?dup
28 IF \ Read error?
29 nip
30 ELSE ( u )
31 0=
32 IF \ End of file?
33 0
34 ELSE
35 a c@ \n = ( is-it-a-\n? )
36 IF 0
37 ELSE f unread
38 THEN
39 THEN
40 THEN
593eb738
HE
41;
42
43\ This is just s\" \n" but s\" isn't yet available.
44create (LINE-TERMINATOR) \n c,
45: LINE-TERMINATOR ( -- c-addr u ) (line-terminator) 1 ;
46
47}private
48
49
50\ This treats \n, \r\n, and \r as line terminator. Reading is done
51\ one char at a time with READ-FILE hence READ-FILE should probably do
52\ some form of buffering for good efficiency.
53: READ-LINE ( c-addr u1 fileid -- u2 flag ior )
aad4537d
HE
54 { a u f }
55 u 0 ?DO
56 a i chars + 1 f read-file ( u ior' )
57 ?dup IF nip i false rot UNLOOP EXIT THEN \ Read error? ( u )
58 0= IF i i 0> 0 UNLOOP EXIT THEN \ End of file? ( )
59 a i chars + c@
60 CASE
61 \n OF i true 0 UNLOOP EXIT ENDOF
62 \r OF
63 \ Detect \r\n
64 a i 1+ chars + f skip-\n ( ior )
65 ?dup IF i false rot UNLOOP EXIT THEN \ IO Error? ( )
66 i true 0 UNLOOP EXIT
67 ENDOF
68 ENDCASE
69 LOOP
70 \ Line doesn't fit in buffer
71 u true 0
593eb738
HE
72;
73
74: WRITE-LINE ( c-addr u fileid -- ior )
aad4537d
HE
75 { f }
76 f write-file ( ior )
77 ?dup
78 IF \ IO error
79 ELSE line-terminator f write-file
80 THEN
593eb738
HE
81;
82
83privatize