Add open-file and close-file

This commit is contained in:
Koichi Nakamura 2021-01-06 02:12:47 +09:00
parent 7aa4b2bd09
commit 145faaf502
3 changed files with 47 additions and 16 deletions

View file

@ -1374,8 +1374,8 @@ decimal
\ file access methods (fam)
0x00 constant R/O \ read-only
0x01 constant R/W \ read-write
0x02 constant W/O \ write-only
0x01 constant W/O \ write-only
0x02 constant R/W \ read-write
\ File
struct
@ -1944,24 +1944,15 @@ codegen-target @ s" i386-linux" str= [if]
( === File I/O === )
5 constant SYS_OPEN
6 constant SYS_CLOSE
: fam-to-mode ( fam -- u )
case
R/O of 0x00 endof
W/O of 0x01 endof
R/W of 0x02 endof
FILE-IO-ERROR throw
endcase
;
5 constant SYS-OPEN
6 constant SYS-CLOSE
: (open-file) ( c-addr fam -- obj f )
fam-to-mode swap SYS_OPEN syscall2 dup 0>=
swap SYS-OPEN syscall2 dup 0>=
;
: (close-file) ( obj -- f)
SYS_CLOSE syscall1 0>=
: (close-file) ( obj -- f )
SYS-CLOSE syscall1 0>=
;
[else] \ i386-linux

View file

@ -8,6 +8,10 @@
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
typedef uintptr_t cell;
typedef void (**cfa)();
@ -153,5 +157,19 @@ defbinary("|", or, |, uintptr_t)
defbinary("^", xor, ^, uintptr_t)
defbinary("<", lt, <, intptr_t)
defbinary("=", eq, ==, intptr_t)
defcode("(open-file)", openfile) {
int flags = pop();
char *name = (char*) pop();
int fd = open(name, flags);
push(fd);
push(fd >= 0);
next();
}
defcode("(close-file)", closefile) {
int fd = pop();
int r = close(fd);
push(r >= 0);
next();
}
#endif

View file

@ -3,6 +3,7 @@
# Copyright (C) 2021 nineties
#
import os
import sys
import operator
@ -60,6 +61,15 @@ def comma_string(s):
comma_byte(ord(c))
comma_byte(0)
def read_string(addr):
s = ""
while True:
c = read_byte(addr)
if c == 0: break
s += chr(c)
addr += 1
return s
def find(c):
it = read(LATEST_CELL)
while it != 0:
@ -197,6 +207,18 @@ def argv():
push(ARGV_ADDR)
push(len(sys.argv))
add_simple_operator('v', argv)
def openfile():
flag = pop()
name = read_string(pop())
fd = os.open(name, flag)
push(fd)
push(fd >= 0)
def closefile():
fd = pop()
os.close(fd)
push(fd >= 0)
add_simple_operator('(open-file)', openfile)
add_simple_operator('(close-file)', closefile)
start = read(HERE_CELL)
comma(find('k'))