source: trunk/libtransmission/ggets.c @ 8050

Last change on this file since 8050 was 6795, checked in by charles, 13 years ago

run libT, cli, daemon, gtk through the source-code formatter "uncrustify" as promised/threatened

File size: 2.4 KB
Line 
1/* File ggets.c  - goodgets is a safe alternative to gets */
2/* By C.B. Falconer.  Public domain 2002-06-22            */
3/*    attribution appreciated.                            */
4
5/* Revised 2002-06-26  New prototype.
6           2002-06-27  Incomplete final lines
7           2006-06-14  Simplified, using getc, not fgets
8           2006-06-15  Fixed memory leak at EOF
9 */
10
11/* fggets and ggets [which is fggets(ln, stdin)] set *ln to
12   a buffer filled with the next complete line from the text
13   stream f.  The storage has been allocated within fggets,
14   and is normally reduced to be an exact fit.  The trailing
15   \n has been removed, so the resultant line is ready for
16   dumping with puts.  The buffer will be as large as is
17   required to hold the complete line.
18
19   Note: this means a final file line without a \n terminator
20   has an effective \n appended, as EOF occurs within the read.
21
22   If no error occurs fggets returns 0.  If an EOF occurs on
23   the input file, EOF is returned.  For memory allocation
24   errors some positive value is returned.  In this case *ln
25   may point to a partial line.  For other errors memory is
26   freed and *ln is set to NULL.
27
28   Freeing of assigned storage is the callers responsibility
29 */
30
31#include <stdio.h>
32#include <stdlib.h>
33#include "ggets.h"
34
35#define INITSIZE   112  /* power of 2 minus 16, helps malloc */
36#define DELTASIZE ( INITSIZE + 16 )
37
38enum {OK = 0, NOMEM};
39
40int
41fggets( char* *ln,
42        FILE * f )
43{
44    int   cursize, ch, ix;
45    char *buffer, *temp;
46
47    *ln = NULL; /* default */
48    if( NULL == ( buffer = malloc( INITSIZE ) ) ) return NOMEM;
49    cursize = INITSIZE;
50
51    ix = 0;
52    while( ( EOF != ( ch = getc( f ) ) ) && ( '\n' != ch ) )
53    {
54        if( ix >= ( cursize - 1 ) ) /* extend buffer */
55        {
56            cursize += DELTASIZE;
57            if( NULL == ( temp = realloc( buffer, (size_t)cursize ) ) )
58            {
59                /* ran out of memory, return partial line */
60                buffer[ix] = '\0';
61                *ln = buffer;
62                return NOMEM;
63            }
64            buffer = temp;
65        }
66        buffer[ix++] = ch;
67    }
68
69    if( ( EOF == ch ) && ( 0 == ix ) )
70    {
71        free( buffer );
72        return EOF;
73    }
74
75    buffer[ix] = '\0';
76    if( NULL == ( temp = realloc( buffer, (size_t)ix + 1 ) ) )
77    {
78        *ln = buffer; /* without reducing it */
79    }
80    else *ln = temp;
81    return OK;
82} /* fggets */
83
84/* End of ggets.c */
Note: See TracBrowser for help on using the repository browser.