]> pd.if.org Git - pdclib/blob - functions/stdio/gets.c
798df766c08590d1d3953667714f3331a105becb
[pdclib] / functions / stdio / gets.c
1 /* $Id$ */
2
3 /* gets( char * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdio.h>
10
11 #ifndef REGTEST
12 #include <_PDCLIB_io.h>
13 #include <stdint.h>
14
15 char * gets( char * s )
16 {
17     _PDCLIB_flockfile( stdin );
18     if ( _PDCLIB_prepread( stdin ) == EOF )
19     {
20         _PDCLIB_funlockfile( stdin );
21         return NULL;
22     }
23     char * dest = s;
24     
25     dest += _PDCLIB_getchars( dest, SIZE_MAX, '\n', stdin );
26     _PDCLIB_funlockfile( stdin );
27
28     if(*(dest - 1) == '\n') {
29         *(--dest) = '\0';
30     } else {
31         *dest = '\0';
32     }
33
34     return ( dest == s ) ? NULL : s;
35 }
36
37 #endif
38
39 #ifdef TEST
40 #include <_PDCLIB_test.h>
41 #include <string.h>
42
43 int main( void )
44 {
45     FILE * fh;
46     char buffer[10];
47     char const * gets_test = "foo\nbar\0baz\nweenie";
48     TESTCASE( ( fh = fopen( testfile, "wb" ) ) != NULL );
49     TESTCASE( fwrite( gets_test, 1, 18, fh ) == 18 );
50     TESTCASE( fclose( fh ) == 0 );
51     TESTCASE( ( fh = freopen( testfile, "rb", stdin ) ) != NULL );
52     TESTCASE( gets( buffer ) == buffer );
53     TESTCASE( strcmp( buffer, "foo" ) == 0 );
54     TESTCASE( gets( buffer ) == buffer );
55     TESTCASE( memcmp( buffer, "bar\0baz\0", 8 ) == 0 );
56     TESTCASE( gets( buffer ) == buffer );
57     TESTCASE( strcmp( buffer, "weenie" ) == 0 );
58     TESTCASE( feof( fh ) );
59     TESTCASE( fseek( fh, -1, SEEK_END ) == 0 );
60     TESTCASE( gets( buffer ) == buffer );
61     TESTCASE( strcmp( buffer, "e" ) == 0 );
62     TESTCASE( feof( fh ) );
63     TESTCASE( fseek( fh, 0, SEEK_END ) == 0 );
64     TESTCASE( gets( buffer ) == NULL );
65     TESTCASE( fclose( fh ) == 0 );
66     TESTCASE( remove( testfile ) == 0 );
67     return TEST_RESULTS;
68 }
69
70 #endif
71