]> pd.if.org Git - pdclib/blob - functions/stdio/fgets.c
Test driver (and much-needed fixes) to fgets().
[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 == 0 )
19     {
20         return NULL;
21     }
22     if ( size == 1 )
23     {
24         *s = '\0';
25         return s;
26     }
27     if ( _PDCLIB_prepread( stream ) == EOF )
28     {
29         return NULL;
30     }
31     char * dest = s;
32     while ( ( ( *dest++ = stream->buffer[stream->bufidx++] ) != '\n' ) && --size > 0 )
33     {
34         if ( stream->bufidx == stream->bufend )
35         {
36             if ( _PDCLIB_fillbuffer( stream ) == EOF )
37             {
38                 /* In case of error / EOF before a character is read, this
39                    will lead to a \0 be written anyway. Since the results
40                    are "indeterminate" by definition, this does not hurt.
41                 */
42                 break;
43             }
44         }
45     }
46     *dest = '\0';
47     return ( dest == s ) ? NULL : s;
48 }
49
50 #endif
51
52 #ifdef TEST
53 #include <_PDCLIB_test.h>
54 #include <string.h>
55
56 int main( void )
57 {
58     FILE * fh;
59     char buffer[10];
60     char const * fgets_test = "foo\nbar\0baz\nweenie";
61     TESTCASE( ( fh = fopen( testfile, "wb+" ) ) != NULL );
62     TESTCASE( fwrite( fgets_test, 1, 18, fh ) == 18 );
63     rewind( fh );
64     TESTCASE( fgets( buffer, 10, fh ) == buffer );
65     TESTCASE( strcmp( buffer, "foo\n" ) == 0 );
66     TESTCASE( fgets( buffer, 10, fh ) == buffer );
67     TESTCASE( memcmp( buffer, "bar\0baz\n", 8 ) == 0 );
68     TESTCASE( fgets( buffer, 10, fh ) == buffer );
69     TESTCASE( strcmp( buffer, "weenie" ) == 0 );
70     TESTCASE( feof( fh ) );
71     TESTCASE( fseek( fh, -1, SEEK_END ) == 0 );
72     TESTCASE( fgets( buffer, 1, fh ) == buffer );
73     TESTCASE( strcmp( buffer, "" ) == 0 );
74     TESTCASE( fgets( buffer, 0, fh ) == NULL );
75     TESTCASE( ! feof( fh ) );
76     TESTCASE( fgets( buffer, 1, fh ) == buffer );
77     TESTCASE( strcmp( buffer, "" ) == 0 );
78     TESTCASE( ! feof( fh ) );
79     TESTCASE( fgets( buffer, 2, fh ) == buffer );
80     TESTCASE( strcmp( buffer, "e" ) == 0 );
81     TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
82     TESTCASE( fgets( buffer, 2, fh ) == NULL );
83     TESTCASE( feof( fh ) );
84     TESTCASE( fclose( fh ) == 0 );
85     remove( testfile );
86     return TEST_RESULTS;
87 }
88
89 #endif
90