K
Keith Thompson
Chris Torek said:In this case, this is just what you want. If you were actually
trying to interpret whole input lines -- as is often the case when
reading input from a human being who is typing commands -- it is
probably not what you want, as the loop might look more like:
while (fgets(buf, sizeof buf, fp) != NULL) {
... code to interpret a command ...
}
and you probably do not want to interpret "he", then "ll", then
"o\n" as three separate commands. In this case you would (a) need
a bigger buffer, and (b) need to double-check to see whether the
human managed to type in an overly long input line despite the
bigger buffer.
And (c) decide what the program should do if the human types in an
overly long input lines. There are numerous possibilities: silently
discard the extra characters, print an error message and abort, print
an error message and continue, build up a longer string containing all
the input (probably using realloc()). In a small toy program, you can
get away with ignoring the issue. In the real world, you had better
decide how to handle it, and write and test the code to do it.
BTW, there are a number of implementations floating around of
functions that read an input line of arbitrary length into a
dynamically allocated buffer.