Utilities/RB_ReadWholeLine [ Functions ]

FUNCTION

Read a line from the file using the provided buffer.

INPUTS

RETURN VALUE

NOTES

If the line did not end in a new line (NL) character one is added.

SOURCE

char               *RB_ReadWholeLine(
    FILE *file,
    char *buf,
    int *arg_readChars )
{
    int                 foundNL = 0;
    char               *line = NULL;
    int                 curLineLen = 1;
    int                 chunkLen = 0;

    clearerr( file );
    while ( ( !feof( file ) ) && ( !foundNL ) )
    {
        *buf = '\0';
        /* read next chunk */
        fgets( buf, MAX_LINE_LEN, file );
        if ( ferror( file ) )
        {
            /* an error occurred */
            RB_Panic( "I/O error %d! RB_ReadWholeLine()", errno );
        }
        chunkLen = strlen( buf );
        curLineLen += chunkLen;
        /* make room for the chunk in our buffer */
        if ( ( line = realloc( line, sizeof( char ) * curLineLen ) ) == NULL )
        {
            /* we run out of memory */
            RB_Panic( "Out of memory! RB_ReadWholeLine()" );
        }
        /* append the chunk to our buffer */
        strcpy( ( line + curLineLen - chunkLen - 1 ), buf );

        if ( RB_ContainsNL( buf ) )
        {
            /* we are done - a line was read */
            foundNL = 1;
        }
    }

    if ( !foundNL )
    {
        /* last line has no NL - add one */
        ++curLineLen;
        if ( ( line = realloc( line, sizeof( char ) * curLineLen ) ) == NULL )
        {
            /* we run out of memory */
            RB_Panic( "Out of memory! RB_ReadWholeLine()" );
        }
        line[curLineLen - 2] = '\n';
        line[curLineLen - 1] = '\0';
    }

    /* This fixes any cr/lf problems. */
    curLineLen -= CR_LF_Conversion( line );

    *arg_readChars = curLineLen;
    *buf = '\0';
    return line;
}