3 /* fgets( char *, int, FILE * )
5 This file is part of the Public Domain C Library (PDCLib).
6 Permission is granted to use, modify, and / or redistribute at will.
13 #include <_PDCLIB_glue.h>
15 char * fgets( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
26 if ( _PDCLIB_prepread( stream ) == EOF )
31 while ( ( ( *dest++ = stream->buffer[stream->bufidx++] ) != '\n' ) && --size > 0 )
33 if ( stream->bufidx == stream->bufend )
35 if ( _PDCLIB_fillbuffer( stream ) == EOF )
37 /* In case of error / EOF before a character is read, this
38 will lead to a \0 be written anyway. Since the results
39 are "indeterminate" by definition, this does not hurt.
46 return ( dest == s ) ? NULL : s;
52 #include <_PDCLIB_test.h>
59 char const * fgets_test = "foo\nbar\0baz\nweenie";
60 TESTCASE( ( fh = fopen( testfile, "wb+" ) ) != NULL );
61 TESTCASE( fwrite( fgets_test, 1, 18, fh ) == 18 );
63 TESTCASE( fgets( buffer, 10, fh ) == buffer );
64 TESTCASE( strcmp( buffer, "foo\n" ) == 0 );
65 TESTCASE( fgets( buffer, 10, fh ) == buffer );
66 TESTCASE( memcmp( buffer, "bar\0baz\n", 8 ) == 0 );
67 TESTCASE( fgets( buffer, 10, fh ) == buffer );
68 TESTCASE( strcmp( buffer, "weenie" ) == 0 );
69 TESTCASE( feof( fh ) );
70 TESTCASE( fseek( fh, -1, SEEK_END ) == 0 );
71 TESTCASE( fgets( buffer, 1, fh ) == buffer );
72 TESTCASE( strcmp( buffer, "" ) == 0 );
73 TESTCASE( fgets( buffer, 0, fh ) == NULL );
74 TESTCASE( ! feof( fh ) );
75 TESTCASE( fgets( buffer, 1, fh ) == buffer );
76 TESTCASE( strcmp( buffer, "" ) == 0 );
77 TESTCASE( ! feof( fh ) );
78 TESTCASE( fgets( buffer, 2, fh ) == buffer );
79 TESTCASE( strcmp( buffer, "e" ) == 0 );
80 TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
81 TESTCASE( fgets( buffer, 2, fh ) == NULL );
82 TESTCASE( feof( fh ) );
83 TESTCASE( fclose( fh ) == 0 );
84 TESTCASE( remove( testfile ) == 0 );