X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdio%2Ffgets.c;h=a82818ad23542f9eaef5a14abc1883913b1024a5;hb=393020b6e48719d27699dea6b29e53025bbd5123;hp=b7e0faa7bf51f5464e9432a30994d0a8a30e389a;hpb=34893ecc2200dc7017c36a54cb6c5f4c2378b5ec;p=pdclib diff --git a/functions/stdio/fgets.c b/functions/stdio/fgets.c index b7e0faa..a82818a 100644 --- a/functions/stdio/fgets.c +++ b/functions/stdio/fgets.c @@ -1,8 +1,60 @@ -// ---------------------------------------------------------------------------- -// $Id$ -// ---------------------------------------------------------------------------- -// Public Domain C Library - http://pdclib.sourceforge.net -// This code is Public Domain. Use, modify, and redistribute at will. -// ---------------------------------------------------------------------------- - -char * fgets( char * restrict s, int n, FILE * restrict stream ) { /* TODO */ }; +/* $Id$ */ + +/* 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. +*/ + +#include + +#ifndef REGTEST + +#define _PDCLIB_GLUE_H _PDCLIB_GLUE_H +#include <_PDCLIB_glue.h> + +char * fgets( char * s, int size, struct _PDCLIB_file_t * stream ) +{ + 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( stdin ) == EOF ) + { + return NULL; + } + char * dest = s; + while ( ( ( *dest = stdin->buffer[stdin->bufidx++] ) != '\n' ) && --size > 0 ) + { + if ( stdin->bufidx == stdin->bufend ) + { + if ( _PDCLIB_fillbuffer( stdin ) == 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 + +#ifdef TEST +#include <_PDCLIB_test.h> + +int main( void ) +{ + TESTCASE( NO_TESTDRIVER ); + return TEST_RESULTS; +} + +#endif +