Path: utzoo!censor!isgtec!robert From: robert@isgtec.UUCP (Robert Osborne) Newsgroups: comp.lang.c Subject: Re: Trouble at EOF Message-ID: <1146@isgtec.UUCP> Date: 18 Jun 91 16:51:54 GMT Sender: news@isgtec.UUCP Reply-To: robert@isgtec.UUCP Lines: 55 In article <4739@inews.intel.com>, bhoughto@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@isgtec.uucp