]> pd.if.org Git - pdclib/blob - functions/stdio/fgets.c
Comment cleanups.
[pdclib] / functions / stdio / fgets.c
1 /* fgets( char *, 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
11 #include <_PDCLIB_glue.h>
12
13 char * fgets( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
14 {
15     if ( size == 0 )
16     {
17         return NULL;
18     }
19     if ( size == 1 )
20     {
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                 /* In case of error / EOF before a character is read, this
36                    will lead to a \0 be written anyway. Since the results
37                    are "indeterminate" by definition, this does not hurt.
38                 */
39                 break;
40             }
41         }
42     }
43     *dest = '\0';
44     return ( dest == s ) ? NULL : s;
45 }
46
47 #endif
48
49 #ifdef TEST
50 #include <_PDCLIB_test.h>
51 #include <string.h>
52
53 int main( void )
54 {
55     FILE * fh;
56     char buffer[10];
57     char const * fgets_test = "foo\nbar\0baz\nweenie";
58     TESTCASE( ( fh = fopen( testfile, "wb+" ) ) != NULL );
59     TESTCASE( fwrite( fgets_test, 1, 18, fh ) == 18 );
60     rewind( fh );
61     TESTCASE( fgets( buffer, 10, fh ) == buffer );
62     TESTCASE( strcmp( buffer, "foo\n" ) == 0 );
63     TESTCASE( fgets( buffer, 10, fh ) == buffer );
64     TESTCASE( memcmp( buffer, "bar\0baz\n", 8 ) == 0 );
65     TESTCASE( fgets( buffer, 10, fh ) == buffer );
66     TESTCASE( strcmp( buffer, "weenie" ) == 0 );
67     TESTCASE( feof( fh ) );
68     TESTCASE( fseek( fh, -1, SEEK_END ) == 0 );
69     TESTCASE( fgets( buffer, 1, fh ) == buffer );
70     TESTCASE( strcmp( buffer, "" ) == 0 );
71     TESTCASE( fgets( buffer, 0, fh ) == NULL );
72     TESTCASE( ! feof( fh ) );
73     TESTCASE( fgets( buffer, 1, fh ) == buffer );
74     TESTCASE( strcmp( buffer, "" ) == 0 );
75     TESTCASE( ! feof( fh ) );
76     TESTCASE( fgets( buffer, 2, fh ) == buffer );
77     TESTCASE( strcmp( buffer, "e" ) == 0 );
78     TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
79     TESTCASE( fgets( buffer, 2, fh ) == NULL );
80     TESTCASE( feof( fh ) );
81     TESTCASE( fclose( fh ) == 0 );
82     TESTCASE( remove( testfile ) == 0 );
83     return TEST_RESULTS;
84 }
85
86 #endif
87