]> pd.if.org Git - pdclib.old/blob - functions/stdio/ungetc.c
[gandr] s/__lp64__/__LP64__/ to match GCC define
[pdclib.old] / functions / stdio / ungetc.c
1 /* $Id$ */
2
3 /* ungetc( int, FILE * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdio.h>
10
11 #ifndef REGTEST
12 #include <_PDCLIB_io.h>
13
14 int _PDCLIB_ungetc_unlocked( int c, FILE * stream )
15 {
16     if ( c == EOF || stream->ungetidx == _PDCLIB_UNGETCBUFSIZE )
17     {
18         return -1;
19     }
20     return stream->ungetbuf[stream->ungetidx++] = (unsigned char) c;
21 }
22
23 int ungetc( int c, FILE * stream )
24 {
25     _PDCLIB_flockfile( stream );
26     int r = _PDCLIB_ungetc_unlocked( c, stream );
27     _PDCLIB_funlockfile( stream);
28     return r;
29 }
30
31 #endif
32
33 #ifdef TEST
34 #include <_PDCLIB_test.h>
35 #include <stdlib.h>
36
37 const char* hellostr = "Hello, world!";
38
39 int main( void )
40 {
41     // Also see ftell() for some testing
42
43     // PDCLIB-18: fread ignores ungetc
44     size_t bufsz = strlen( hellostr ) + 1;
45     char * buf = malloc( bufsz );
46     FILE * fh;
47
48     // Also fgets
49     TESTCASE( ( fh = tmpfile() ) != NULL );
50     TESTCASE( fputs(hellostr, fh) == 0 );
51     rewind(fh);
52     TESTCASE( fgetc( fh ) == 'H' );
53     TESTCASE( ungetc( 'H', fh ) == 'H' );
54     TESTCASE( fgets( buf, bufsz, fh ) != NULL );
55     TESTCASE( strcmp( buf, hellostr ) == 0 );
56
57     // fread
58     rewind(fh);
59     TESTCASE( fgetc( fh ) == 'H' );
60     TESTCASE( ungetc( 'H', fh ) == 'H' );
61     TESTCASE( fread( buf, bufsz - 1, 1, fh ) == 1 );
62     TESTCASE( strncmp( buf, hellostr, bufsz - 1 ) == 0 );
63
64
65
66     return TEST_RESULTS;
67 }
68
69 #endif