]> git.sur5r.net Git - cc65/blob - libsrc/common/_file.s
Close all open files on exit
[cc65] / libsrc / common / _file.s
1 ;
2 ; Ullrich von Bassewitz, 31.05.1998
3 ;
4 ; Data for the stdio file stream.
5 ;
6 ; Be sure to keep the value priority of closeallstreams lower than that of
7 ; closeallfiles (which is the low level POSIX counterpart and must be
8 ; called after closeallstreams).
9
10         .export         __filetab, _stdin, _stdout, _stderr
11         .destructor     closeallstreams, 16
12         .import         _close
13
14         .include        "fcntl.inc"
15         .include        "_file.inc"
16
17 ;----------------------------------------------------------------------------
18 ; Close all files on exit
19
20 .proc   closeallstreams
21
22         ldy     #((FOPEN_MAX - 1) * _FILE_size)
23 loop:   sty     index                           ; Save the index
24         lda     __filetab + _FILE_f_flags,y     ; Load file flags
25         and     #_FOPEN                         ; Is it open?
26         beq     next                            ; jump if closed
27
28 ; Close this file
29
30         lda     __filetab + _FILE_f_fd,y
31         ldx     #0
32         jsr     _close
33
34 ; Next file
35
36 next:   lda     index
37         sec
38         sbc     #_FILE_size
39         tay
40         bcs     loop
41
42         rts
43
44 .endproc
45
46 ;----------------------------------------------------------------------------
47 ; File data
48
49 .data
50
51 __filetab:
52         .byte   0, _FOPEN       ; stdin
53         .byte   1, _FOPEN       ; stdout
54         .byte   2, _FOPEN       ; stderr
55 .repeat FOPEN_MAX - 3
56         .byte   0, _FCLOSED     ; free slot
57 .endrepeat
58
59
60 ; Standard file descriptors
61
62 _stdin:
63         .word   __filetab + (STDIN_FILENO * _FILE_size)
64
65 _stdout:
66         .word   __filetab + (STDOUT_FILENO * _FILE_size)
67
68 _stderr:
69         .word   __filetab + (STDERR_FILENO * _FILE_size)
70
71
72 ; Temp storage for closeallstreams
73
74 .bss
75 index:  .res    1
76