On Tue, 8 Feb 2005 21:52:32 +0100, "Peter" <pe**@hello.com> wrote:
<snip>
What's the function I'm looking for then to take in any length of string
(whether white space or not)?
Others have already answered what you probably meant to ask, which is
how to input (up to) a line of data possibly containing space, or
perhaps "linear whitespace" or "horizontal whitespace" which includes
tab also. However, the definition of whitespace in C, and also in
(most?) Internet standards, includes newline, and CR and VT and FF. So
your question as stated is actually to read an entire (text) file into
memory -- or an entire TCP (e.g. HTTP) datastream, if on a system
where sockets are interchangeable with files (i.e. Unix) or otherwise
supported by stdio. If that's what you want, the simplest way is just
char buf [BIGENUF];
size_t len;
len = fread (buf, 1, sizeof buf /* or BIGENUF */, fp_eg_stdin);
/* if you want to use the result as a string in C: */
/* do the read for (sizeof buf) -1 (parens not required
but shown for clarity) aka BIGENUF -1 and then */
buf [len] = '\0' /* or just 0 */
If you can't determine in advance (at compile time, or in C99 or GCC
for a local=automatic buffer at declaration which must be before the
read) a buffer size that will be sufficiently large, you must either:
- determine file size, which can't be done fully portably, FAQ 19.12
at the usual places and
http://www.eskimo.com/~scs/C-faq/top.html ,
then malloc that much space, checking for failure (return == NULL) and
handling as appropriate, otherwise read the data
- or, malloc a buffer of some "normal" size and try reading that much,
and if that doesn't reach EOF, realloc to a larger size and read more
etc. until either you get it all or realloc fails (out of memory)
In both cases plus a byte for a null terminator if you want a string.
- David.Thompson1 at worldnet.att.net