1 /* fgets( char *, int, FILE * )
3 This file is part of the Public Domain C Library (PDCLib).
4 Permission is granted to use, modify, and / or redistribute at will.
11 #include <_PDCLIB_glue.h>
13 char * fgets( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
24 if ( _PDCLIB_prepread( stream ) == EOF )
29 while ( ( ( *dest++ = stream->buffer[stream->bufidx++] ) != '\n' ) && --size > 0 )
31 if ( stream->bufidx == stream->bufend )
33 if ( _PDCLIB_fillbuffer( stream ) == EOF )
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.
44 return ( dest == s ) ? NULL : s;
50 #include <_PDCLIB_test.h>
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 );
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 );