]> pd.if.org Git - pdclib/blob - functions/stdio/fgets.c
a3c41e94085eb3f8fa610d57c926dfa8115c36ef
[pdclib] / functions / stdio / fgets.c
1 /* $Id$ */
2
3 /* fgets( char *, 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 #define _PDCLIB_GLUE_H _PDCLIB_GLUE_H
14 #include <_PDCLIB_glue.h>
15
16 char * fgets( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
17 {
18     if ( size <= 1 )
19     {
20         /* TODO: This is the letter of the standard, but is it the right thing to do? */
21         *s = '\0';
22         return s;
23     }
24     if ( _PDCLIB_prepread( stream ) == EOF )
25     {
26         return NULL;
27     }
28     char * dest = s;
29     while ( ( ( *dest = stream->buffer[stream->bufidx++] ) != '\n' ) && --size > 0 )
30     {
31         if ( stream->bufidx == stream->bufend )
32         {
33             if ( _PDCLIB_fillbuffer( stream ) == EOF )
34             {
35                 /* EOF adds \0, error leaves target indeterminate, so we can
36                    just add the \0 anyway.
37                 */
38                 *dest = '\0';
39                 return NULL;
40             }
41         }
42         ++dest;
43     }
44     *dest = '\0';
45     return s;
46 }
47
48 #endif
49
50 #ifdef TEST
51 #include <_PDCLIB_test.h>
52
53 int main( void )
54 {
55     TESTCASE( NO_TESTDRIVER );
56     return TEST_RESULTS;
57 }
58
59 #endif
60