Path: utzoo!utgpu!watmath!clyde!att!ulysses!ggs From: ggs@ulysses.homer.nj.att.com (Griff Smith) Newsgroups: comp.lang.c Subject: Re: retiring gets(3) Summary: you may be trading bugs Message-ID: <10843@ulysses.homer.nj.att.com> Date: 11 Nov 88 21:40:09 GMT References: <8847@smoke.BRL.MIL> <9054@ihlpb.ATT.COM> Organization: AT&T Bell Laboratories, Murray Hill Lines: 40 In article <9054@ihlpb.ATT.COM>, gregg@ihlpb.ATT.COM (Wonderly) writes: > I believe that the right thing to do is to use a new function called > nlfgets (str, size, fp), that does exactly as gets(3). The biggest > concern that most people have about moving from gets to fgets is the > added hassle of doing a | > if ((t = strchr (buf, '\n')) != NULL) > *t = 0; | > This seems to be a lot of work when you may be processing thousands of > lines of code. I have written this exact function many times just to > have the benefit of no strchr() call. > -- > It isn't the DREAM that NASA's missing... DOMAIN: gregg@ihlpb.att.com > It's a direction! UUCP: att!ihlpb!gregg I think this misses the point. Gets guarantees that you will read all the characters in a line, but forces you to write insecure programs. One must also make the dubious assumption that the first null encountered is the terminal null rather than a null in the file. Your variation avoids the security problem, but preserves the ambiguity of nulls. It also adds another ambiguity: if someone hands you a line that is longer than your buffer, you gratuitously break it into two lines since you don't know where the newline is. Fgets avoids all these problems by marking the end of a line with newline. Proper use requires that you call fgets until you find the newline. You may need to use malloc as you discover that the line is much larger than anticipated. Fgets does have one annoying flaw: it should return the character count instead of the worthless pointer to the destination. If you complain that all this fuss is unnecessary, since all reasonable input will fit in the buffer you provided, you are really saying you don't like to write correct programs. I sometimes settle for `partially correct': a program must either operate as specified or stop. Breaking lines isn't even partially correct. -- Griff Smith AT&T (Bell Laboratories), Murray Hill Phone: 1-201-582-7736 UUCP: {most AT&T sites}!ulysses!ggs Internet: ggs@ulysses.att.com