X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdio%2Ffgets.c;h=a3c41e94085eb3f8fa610d57c926dfa8115c36ef;hb=e9a6658165caf38491a04d17a04accec11a3696c;hp=203d3ff0306643de6527de273556f155266a36a1;hpb=e5112b619d1aae8ffc439389cfcbd3b2b4bd2454;p=pdclib diff --git a/functions/stdio/fgets.c b/functions/stdio/fgets.c index 203d3ff..a3c41e9 100644 --- a/functions/stdio/fgets.c +++ b/functions/stdio/fgets.c @@ -1,6 +1,6 @@ /* $Id$ */ -/* fgets( char *, int, FILE * ); +/* fgets( char *, int, FILE * ) This file is part of the Public Domain C Library (PDCLib). Permission is granted to use, modify, and / or redistribute at will. @@ -10,10 +10,39 @@ #ifndef REGTEST -char * fgets( char * _PDCLIB_restrict s, int n, struct _PDCLIB_file_t * _PDCLIB_restrict stream ) +#define _PDCLIB_GLUE_H _PDCLIB_GLUE_H +#include <_PDCLIB_glue.h> + +char * fgets( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCLIB_restrict stream ) { - /* TODO: Implement. */ - return NULL; + if ( size <= 1 ) + { + /* TODO: This is the letter of the standard, but is it the right thing to do? */ + *s = '\0'; + return s; + } + if ( _PDCLIB_prepread( stream ) == EOF ) + { + return NULL; + } + char * dest = s; + while ( ( ( *dest = stream->buffer[stream->bufidx++] ) != '\n' ) && --size > 0 ) + { + if ( stream->bufidx == stream->bufend ) + { + if ( _PDCLIB_fillbuffer( stream ) == EOF ) + { + /* EOF adds \0, error leaves target indeterminate, so we can + just add the \0 anyway. + */ + *dest = '\0'; + return NULL; + } + } + ++dest; + } + *dest = '\0'; + return s; } #endif @@ -28,3 +57,4 @@ int main( void ) } #endif +