Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!bloom-beacon!think!barmar From: barmar@think.COM (Barry Margolin) Newsgroups: comp.lang.c Subject: Re: gets limits? Message-ID: <39707@think.UUCP> Date: 25 Apr 89 19:50:36 GMT References: <9300001@scsmo1.UUCP> Sender: news@think.UUCP Reply-To: barmar@kulla.think.com.UUCP (Barry Margolin) Organization: Thinking Machines Corporation, Cambridge, MA Lines: 43 The only time it is correct to use gets() is when you know for sure the maximum line length. This could be the case if you're reading a file that was written by another program, whose output is in a regular, known format. If you've still got a card reader, it could be useful for reading card images. Gets() should NOT be used when reading user input or files that are likely to have been edited by the user. Of course, since gets() also defaults the stream to standard input, it's likely that most potential uses of gets() would read from the terminal. In other words, it's hardly ever a good idea to use gets(). The most obvious (to me, at least) implementation of gets() doesn't have any limit on the number of characters it will read. It would look something like (please excuse any C syntax errors, I'm mainly a Lisp hacker): char *gets(s) char *s; { int c; while (((c = getchar()) != EOF) && (c != '\n')) *s++ = c; /* Add trailing null */ *s = '\0'; return s; } Since it uses the provided string as its input buffer, it has no inherent limit on the size. But since it isn't given a limit as a parameter, it will go beyond the end of the buffer if the line is too long. And no matter how large you make the buffer, someone can make an input stream with a longer line (some terminal drivers have limits on the size of a single line, but the input could be redirected to a huge file containing no newlines). Barry Margolin Thinking Machines Corp. barmar@think.com {uunet,harvard}!think!barmar