Routine to read arbitrary lenght lines from a stdio file desc.

Jason Venner jason at ucbopal.BERKELEY.EDU
Wed Dec 25 05:52:17 AEST 1985


This routine takes a FILE* as it's sole argument,  and returns a pointer
to a null terminated string in malloced memory.
The string will be terminated be a '\n''\0' if there is a terminating
'\n' in the input,  or just by a '\0' if an 'EOF' was hit.

There should be no problem using this on other UNIX version,  but I don't know.
---Cut Here Checksum via sum.1 is '22377     2'----
#include	<stdio.h>

/*	This routine reads a line (of arbitrary length), up to a '\n' or 'EOF'
 *	and returns a pointer to the resulting null terminated string.
 *	The '\n' if found, is included in the returned string.
 */

#define	STRGROW	256

char	*
readline( fd )
FILE	*fd;
{

	int	c;
	unsigned	StrLen;
	unsigned	MemLen;
	char	*StrPtr;
	char*	realloc();
	
	StrPtr = (char*) 0;
	StrLen = 0;
	MemLen = STRGROW; 
	if( !(StrPtr = realloc( StrPtr, MemLen )) ) {
		return (char*) 0;
	}
	MemLen -= 1;					  /* Save constant -1's in while loop */
	while( (c = getc( fd )) != EOF ) {
		StrPtr[StrLen] = c;
		StrLen++;
		if( StrLen >= MemLen ) {
			MemLen += STRGROW;
			if( !(StrPtr = realloc( StrPtr, MemLen + 1)) ) {
				return (char*) 0;
			}
		}
		if( c == '\n' ) {
			break;
		}
	}
	if( StrLen == 0 ) {
		(void) free( StrPtr );
		return (char*) 0;
	}
	StrPtr[StrLen] = '\0';
										  /* Trim the string */
	if( !(StrPtr = realloc( StrPtr, StrLen + 1 )) ) {
		return (char*) 0;
	}
	return StrPtr;
}

#ifdef	TEST_READLINE
main( argc, argv )
int	argc;
char	**argv;
{
	char	*string;
	while( (string = readline( stdin )) ) {
		puts( string );
		(void) free( string );
	}
	exit( 0 );
}
#endif
---Cut here also----
jason at jade.berkeley.edu
{ihnp4,sun,dual,tektronix}!ucbvax!ucbjade!jason



More information about the Comp.sources.unix mailing list