]> pd.if.org Git - pdclib/blob - functions/stdio/ungetc.c
PDCLIB-18: Add _PDCLIB_getchars to _PDCLIB_io.h. Change fread & fgets to go through...
[pdclib] / 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
13 int ungetc_unlocked( int c, struct _PDCLIB_file_t * stream )
14 {
15     if ( c == EOF || stream->ungetidx == _PDCLIB_UNGETCBUFSIZE )
16     {
17         return -1;
18     }
19     return stream->ungetbuf[stream->ungetidx++] = (unsigned char) c;
20 }
21
22 int ungetc( int c, struct _PDCLIB_file_t * stream )
23 {
24     flockfile( stream );
25     int r = ungetc_unlocked( c, stream );
26     funlockfile( stream);
27     return r;
28 }
29
30 #endif
31
32 #ifdef TEST
33 #include <_PDCLIB_test.h>
34 #include <stdlib.h>
35
36 const char* hellostr = "Hello, world!";
37
38 int main( void )
39 {
40     // Also see ftell() for some testing
41
42     // PDCLIB-18: fread ignores ungetc
43     size_t bufsz = strlen( hellostr ) + 1;
44     char * buf = malloc( bufsz );
45     FILE * fh;
46
47     // Also fgets
48     TESTCASE( ( fh = tmpfile() ) != NULL );
49     TESTCASE( fputs(hellostr, fh) == 0 );
50     rewind(fh);
51     TESTCASE( fgetc( fh ) == 'H' );
52     TESTCASE( ungetc( 'H', fh ) == 'H' );
53     TESTCASE( fgets( buf, bufsz, fh ) != NULL );
54     TESTCASE( strcmp( buf, hellostr ) == 0 );
55
56     // fread
57     rewind(fh);
58     TESTCASE( fgetc( fh ) == 'H' );
59     TESTCASE( ungetc( 'H', fh ) == 'H' );
60     TESTCASE( fread( buf, bufsz - 1, 1, fh ) == 1 );
61     TESTCASE( strncmp( buf, hellostr, bufsz - 1 ) == 0 );
62
63
64
65     return TEST_RESULTS;
66 }
67
68 #endif