#include /* This subroutine will read one line of input from a file. A line is defined to be an arbitrary string of characters that is terminated by a newline character or an end-of-file. If the line from the file exceeds the length provided by maxlen then the rest of the line is read and thrown away. Any error messages are sent to standard error. The return value is the length of the line that was read, excluding the newline character. If the read begins at the end-of-file, this function returns EOF. Warning: this routine assumes that the string termination character '\0' can be stored at s[maxlen+1] if needed. Therefore if you declare the string to be char new_line[80]; the function call should look like n_read = getline(new_line,79); Actually, any value less than 80 will do, just don't use the same number as appears in the declaration. You need to leave one character for the null character. */ int fgetline(fp,s,maxlen) FILE *fp; char *s; int maxlen; { int i=0; /* counts the number of characters read (up to maxlen) */ char c; /* the new character */ int ok=1; /* normally TRUE, if false then the input string was too long */ while ( (c = getc(fp)) != EOF ) { /* Read until end-of-file */ if ( c == '\n' ) { /* If character is a newline, we are done */ *s = '\0'; /* Append end-of-string null */ return(i); /* Return the number read (excluding newline) */ } else if ( ok ) { /* Only pass on the character if we haven't exceeded maxlen */ if ( i >= maxlen ) { /* this detects the error once */ fprintf(stderr,"FGETLINE error: input line longer than %d characters, truncating line.\n",maxlen); ok = 0; } else { /* pass on the character and bump the counter and pointer */ *s++ = c; i++; } } } /* This code is seen only when the end-of-file is hit */ if ( i == 0 ) return( EOF ); else return(i); }