Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.3 4.3bsd-beta 6/6/85; site ucbjade.BERKELEY.EDU Path: utzoo!watmath!clyde!burl!ulysses!ucbvax!ucbjade!ucbopal!jason From: jason@ucbopal.BERKELEY.EDU (Jason Venner) Newsgroups: net.sources Subject: Routine to read arbitrary lenght lines from a stdio file desc. Message-ID: <219@ucbjade.BERKELEY.EDU> Date: Tue, 24-Dec-85 14:52:17 EST Article-I.D.: ucbjade.219 Posted: Tue Dec 24 14:52:17 1985 Date-Received: Wed, 25-Dec-85 23:20:29 EST Sender: network@ucbjade.BERKELEY.EDU Reply-To: jason@ucbopal.BERKELEY.EDU (Jason Venner) Organization: University of California, Berkeley Lines: 76 Keywords: tested 4.3 BSD 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 /* 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@jade.berkeley.edu {ihnp4,sun,dual,tektronix}!ucbvax!ucbjade!jason