Mail Archives: djgpp/1999/01/12/12:15:22
On 11 Jan 1999 18:18:52 GMT, ams AT ludd DOT luth DOT se (Martin Str|mberg) so
kindly spent valuable time writing:
>Stuart Hall (fprintf AT iname DOT com) wrote:
>: I have made an implementation of gets() that is a lot safer than the
>: standard function - it is safer because it won't overrun an array.
>
>You mean like the fgets() function?
Actually fgets() works, but I have read that it doesn't read the
truncate the /n or something. Anyway I am also following along in the
comp.lang.c and alt.comp.lang.learn.c-c++ group and they highly
recommend using the following function as an alternative to both
gets() and fgets(). I think the comp.lang.c FAQ has a pretty good
explanation in there too...
Here is the code snippet and explanation from a regular on that
group... (without permission)
char *
getsafe (char *str, int n)
{
int c = EOF;
char *s = str;
if (str == 0 || n < 0) n = 0;
if (n == 0) str = 0;
else n--;
if (!feof (stdin)) {
while ((c = getchar ()) != '\n' && c != EOF)
if (n > 0) n--, *s++ = c;
if (s) *s = '\0';
}
return (c == '\n') ? str : 0;
}
"The idea is to behave like gets as much as possible. In particular,
it will always read up to the newline, even after the string has
reached its designated limit. Passing in a null string or a non
positive limit to getsafe() discards the (rest of the) input line
without storing anything in the string."
stuart
- ratboy
(don't be surprised if you email me and the response
comes back from somewhere else - iname.com is just a
forwarding service)
- Raw text -