john_bode@my-deja.com (John Bode) wrote in message news:<43618c0e.0309240610.57ce3614@posting.google. com>...[color=blue]
> Xinyi Yang <icg_3@slds1.de.lucent.com> wrote in message news:<3F6ADD69.AD4B26BB@slds1.de.lucent.com>...[color=green]
> > Hi,
> >
> > I have to read information out of a file. The format will be
> > string1,string2,...,
> > string3,string4,...,
> > ...
> > (the string sould not contain ' ' anyway)
> > the size of each string is uncertain. I plan to create an array to contain the pointers to the strings. Yet I don't know how to read a string out from the file any let a pointer point to it. I thought about using char *p=(int *) (malloc(n*(sizeof(char)))), but it means I have to first read the string to get the length, then read again and save it to the array. Is there any better way?
> > I would not like to use array with certain length since I don't know how long could a string be.
> >
> > Thanks in advance!
> >
> > Xinyi[/color]
>
> The way I'd attack this is to create a dynamic buffer of size X using
> malloc(), then reading a single character at a time into the dynamic
> buffer, extending it as necessary using realloc(), until you see
> either a ',' or EOF.
>
> Quick, dirty, untested example:
>
> #include <stdio.h>
> #include <ctype.h>
> #include <stdlib.h>
>
> #define START_SIZE 20 /* Initial buffer size */
> #define EXTENT 5 /* Size to extend buffer by */
>
> char *nextToken (FILE *in)
> {
> char *tmp, *p;
> int phys_size = START_SIZE, cur_size = 0;
> int nextchar;
>
> /*
> ** Note: Do not cast the return value of malloc() unless
> ** you are using a pre-C89 compiler.
> */
> p = malloc (START_SIZE);
>
> if (p)
> {
> /*
> ** consume any leading whitespace
> */
> while (isspace(nextchar = fgetc (in))[/color]
) /* oops */[color=blue]
> /* empty loop */;
>
> while (nextchar != ',' && nextchar != EOF)
> {
> if (cur_size == phys_size - 1)
> {
> /*
> ** We've hit the end of the buffer.
> ** Use realloc() to extend it by
> ** EXTENT characters. For this example,
> ** a realloc() failure is a fatal error
> ** and we exit the program immediately.
> ** With a little effort you could make
> ** this handle such an error more gracefully.
> */
> tmp = realloc (p, phys_size + EXTENT);
> if (!tmp)
> {
> fprintf (stderr, "Buffer extend failed! Fatal
> error!\n");
> fflush (stderr);
> exit (0);
> }
> phys_size += EXTENT;
> p = tmp;
> }
> p[cur_size++] = c;[/color]
p[cur_size++] = nextchar; /* oops^2 */
nextchar = fgetc (in); /* oops^3 */[color=blue]
> }
> p[cur_size] = 0; /* terminate the string */
> }
>
> return p;
> }[/color]