]> git.sur5r.net Git - cc65/blob - libsrc/common/ungetc.s
Merge pull request #740 from laubzega/master
[cc65] / libsrc / common / ungetc.s
1 ;
2 ; Ullrich von Bassewitz, 2004-05-12
3 ;
4 ; int __fastcall__ ungetc (int c, FILE* f);
5 ; /* Push back a character into a file stream. */
6 ;
7
8         .export         _ungetc
9
10         .import         popax
11         .import         ptr1: zp, tmp1: zp
12
13         .include        "_file.inc"
14         .include        "errno.inc"
15
16
17 ; ------------------------------------------------------------------------
18 ; Code
19
20 .proc   _ungetc
21
22 ; Save the file pointer to ptr1
23
24         sta     ptr1
25         stx     ptr1+1
26
27 ; Get c from stack and save the lower byte in tmp1
28
29         jsr     popax
30         sta     tmp1
31
32 ; c must be in char range
33
34         txa
35         bne     error
36
37 ; Check if the file is open
38
39         ldy     #_FILE::f_flags
40         lda     (ptr1),y
41         and     #_FOPEN                 ; Is the file open?
42         beq     error                   ; Branch if no
43
44 ; Set the pushback flag and reset the end-of-file indicator
45
46         lda     (ptr1),y
47         ora     #_FPUSHBACK
48         and     #<~_FEOF
49         sta     (ptr1),y
50
51 ; Store the character into the pushback buffer
52
53         ldy     #_FILE::f_pushback
54         lda     tmp1
55         sta     (ptr1),y
56
57 ; Done, return c
58
59         ldx     #0
60         rts
61
62 ; File is not open or the character is invalid
63
64 error:  lda     #EINVAL
65         jsr     __seterrno
66         lda     #$FF                    ; Return -1
67         tax
68         rts
69
70 .endproc
71