1 /* Time-stamp: <2008-03-14 19:56:20 poser> */
2 /*
3  * Copyright (C) 2008 William J. Poser (billposer@alum.mit.edu)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of version 3 the GNU General Public License
7  * as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17  * or go to the web page:  http://www.gnu.org/licenses/gpl.txt.
18  */
19 
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <ctype.h>
23 
24 /*
25  * Read a chunk of arbitrary length from a file, terminated
26  * by whitespace.
27  *
28  * Return a pointer to the null-terminated string allocated, or null on failure
29  * to allocate sufficient storage.
30  * The length of the word is placed in the variable pointed to by
31  * the second argument.
32  *
33  * It is the responsibility of the caller to free the space allocated.
34  */
35 
36 #define INITLENGTH 16
37 
38 
Get_Word(FILE * fp,char * delim,int * WordLength)39 char * Get_Word(FILE *fp, char *delim, int *WordLength)
40 {
41   int c;
42   int Available;
43   int Chars_Read;
44   char *Word;
45   char Delimiter;
46 
47   Delimiter = *delim;
48   Available = INITLENGTH;
49   Chars_Read=0;
50   Word = (char *) malloc((size_t)Available);
51   if(Word == (char *) 0) return (Word);
52   while(1){
53     c=getc(fp);
54     if(c == EOF){
55       Word[Chars_Read]='\0';
56       *WordLength=Chars_Read;
57       return(Word);
58     }
59     /* For mysterious reasons isspace is sometimes a problem */
60     if((0x20==c)||(0x09==c)||(0x0A==c)||(0x0D==c)){
61       Word[Chars_Read]='\0';
62       *WordLength=Chars_Read;
63       return(Word);
64     }
65     if(c == Delimiter) continue;
66     if(Chars_Read == (Available-1)){ /* -1 because of null */
67       Available += INITLENGTH/2;
68       Word = (char *) realloc( (void *) Word, (size_t) (Available * sizeof (char)));
69       if(Word == (char *) 0) return(Word);
70     }
71     Word[Chars_Read++]= (char) (c & 0x7F);
72   }
73 }
74