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