]> pd.if.org Git - pdclib/blobdiff - functions/stdio/fgets.c
PDCLIB-18: Add _PDCLIB_getchars to _PDCLIB_io.h. Change fread & fgets to go through...
[pdclib] / functions / stdio / fgets.c
index 1afd79f6ed7ed50426dadd32414d3a5c1f851df3..6fbc2ef7961509b7e0c93aeae610d001f1a84f90 100644 (file)
 
 #ifndef REGTEST
 
-#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 )
+char * fgets_unlocked( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
 {
     if ( size == 0 )
     {
@@ -29,24 +28,22 @@ char * fgets( char * _PDCLIB_restrict s, int size, struct _PDCLIB_file_t * _PDCL
         return NULL;
     }
     char * dest = s;
-    while ( ( ( *dest++ = stream->buffer[stream->bufidx++] ) != '\n' ) && --size > 0 )
-    {
-        if ( stream->bufidx == stream->bufend )
-        {
-            if ( _PDCLIB_fillbuffer( stream ) == EOF )
-            {
-                /* In case of error / EOF before a character is read, this
-                   will lead to a \0 be written anyway. Since the results
-                   are "indeterminate" by definition, this does not hurt.
-                */
-                break;
-            }
-        }
-    }
+
+    dest += _PDCLIB_getchars( dest, size - 1, '\n', stream );
+
     *dest = '\0';
     return ( dest == s ) ? NULL : s;
 }
 
+char * fgets( char * _PDCLIB_restrict s, int size, 
+              struct _PDCLIB_file_t * _PDCLIB_restrict stream )
+{
+    flockfile( stream );
+    char* r = fgets_unlocked( s, size, stream );
+    funlockfile( stream );
+    return r;
+}
+
 #endif
 
 #ifdef TEST
@@ -82,7 +79,7 @@ int main( void )
     TESTCASE( fgets( buffer, 2, fh ) == NULL );
     TESTCASE( feof( fh ) );
     TESTCASE( fclose( fh ) == 0 );
-    remove( testfile );
+    TESTCASE( remove( testfile ) == 0 );
     return TEST_RESULTS;
 }