Trouble at EOF
Robert Osborne
robert at isgtec.UUCP
Wed Jun 19 02:51:54 AEST 1991
In article <4739 at inews.intel.com>, bhoughto at pima.intel.com (Blair P. Houghton) writes:
> Yes, fgets at eof may get a line with no newline.
>
> Hence:
>
> while ( fgets(s, sizeof s, stream) )
> /* not eof */
> process(s);
Well you really want...
if( fgets(s, sizeof s, stream) ) {
do {
process(s);
} while ( fgets(s, sizeof s, stream) );
}
or something similar.
> /* reached iff eof */
> if ( strlen(s) != 0 ) {
> /* there's something left to process */
> if ( s[strlen(s) - 1] != '\n' )
> /* it has no newline */
> strcat(s,"\n");
> process(s);
> }
This has two str??? calls too many...
/* reached iff eof */
if ( (s_length = strlen(s)) != 0 ) {
/* there's something left to process */
if ( s[s_length - 1] != '\n' ) {
/* it has no newline */
s[s_length] = '\n';
s[s_length + 1] = '\0';
}
process(s);
}
The str??? calls are OFTEN used in this manner and this is a very
common optimization that can be made in string handlers.
I once cut the running time of a key piece of UI functionality from
an intolerable >10 seconds to an almost bearable <5 seconds by performing
this kind of "optimization".
> But notice also that the size of the gotten string is
> limited to the number of chars specified in the second
> argument to fgets.
And this would be intolerable in a parser. I'm surprised Blair didn't
mention this (although he did solve the problem asked).
Rob.
--
Robert A. Osborne ...uunet!utai!lsuc!isgtec!robert or robert at isgtec.uucp
More information about the Comp.lang.c
mailing list