In the spirit of hacking quick answers, here is the "sgets" I just wrote. It tries to emulate fgets, but with string input.
Edit The bug Monte pointed out (thanks) has been fixed. Madly gaining utility, believing that at least 15 other people with the same idea are desperate to do the same, do not lead to a well-tested code. Poorly. The original version included a newline on a subsequent call.
char *sgets( char * str, int num, char **input ) { char *next = *input; int numread = 0; while ( numread + 1 < num && *next ) { int isnewline = ( *next == '\n' ); *str++ = *next++; numread++; // newline terminates the line but is included if ( isnewline ) break; } if ( numread == 0 ) return NULL; // "eof" // must have hit the null terminator or end of line *str = '\0'; // null terminate this tring // set up input for next call *input = next; return str; } int main( int argc, char* argv[] ) { // quick and dirty test char *str = "abc\ndefghitjklksd\na\n12345\n12345\n123456\nabc\n\n"; char buf[5]; while ( sgets( buf, sizeof( buf ), &str )) printf( "'%s'\n", buf ); }
Mark wilkins
source share