int ReadInputToTree(
WORD **DestTree,
size_t *Treecount,
FILE *Input)
{
int Status = SUCCESS;
char *Buf = NULL;
size_t bufsize = 0;
char *Word = NULL;
char *bufbase = NULL;
char *tmp = NULL;
if (Input != stdin)
{
size_t tmp = ftell(Input);
fseek(Input, 0, SEEK_END);
bufsize = ftell(Input);
fseek(Input, tmp, SEEK_SET);
Buf = (char*)malloc(bufsize);
if (Buf == NULL)
{
Status = NO_MEMORY_FOR_WORDNODE;
goto end;
}
if (fread(Buf, sizeof(char), bufsize, Input) != bufsize)
{
printf("The promised amount was not read.\n");
exit(1);
}
}
else
{
bufsize = 256;
Buf = calloc(bufsize, sizeof(char));
if (Buf == NULL)
{
Status = NO_MEMORY_FOR_WORDNODE;
goto end;
}
bufbase = Buf;
while (fgets(Buf, (int)(bufsize - (Buf - bufbase)), Input) != NULL)
{
Buf += (int)(bufsize - (Buf - bufbase)) -1;
if (bufbase[bufsize - 2] != 0)
{
tmp = (char*)realloc(bufbase, bufsize * 2);
if (tmp == NULL)
{
Status = NO_MEMORY_FOR_WORDNODE;
goto end;
}
Buf = tmp + (Buf - bufbase);
bufbase = tmp;
bufsize *= 2;
bufbase[bufsize - 2] = 0;
}
Buf = bufbase + strlen(bufbase);
}
Buf = bufbase;
}
Word = strtok(Buf, NONALPHA);
while (Status == SUCCESS && Word != NULL)
{
Status = AddToTree(DestTree, Treecount, Word);
if (Status == SUCCESS)
{
Word = strtok(NULL, NONALPHA);
}
}
goto end;
end:
free(Buf);
free(bufbase);
return (Status);
}