File: GetWord.c

package info (click to toggle)
uni2ascii 4.20-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 992 kB
  • sloc: ansic: 8,730; sh: 4,471; tcl: 1,914; python: 53; makefile: 42
file content (59 lines) | stat: -rw-r--r-- 1,477 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

/* 
 * Read a chunk of arbitrary length from a file, terminated
 * by whitespace.
 *
 * Return a pointer to the null-terminated string allocated, or null on failure
 * to allocate sufficient storage.
 * The length of the word is placed in the variable pointed to by
 * the second argument.
 *
 * On EOF, the eof flag in the third command line argument is set.
 * It is the responsibility of the caller to free the space allocated.
 */

#define INITLENGTH 16


unsigned long GetWordLineNo;

char * Get_Word(FILE *fp, int *WordLength,int *eofptr)
{
  int c;
  int Available;
  int CharsRead;
  char *Word;

  Available = INITLENGTH;
  CharsRead=0;
  Word = (char *) malloc((size_t)Available);
  if(Word == NULL) return (Word);
  
  *eofptr = 0;
  while(1){
    c=getc(fp);
    //    if(isspace(c)) {
    if ( (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r') || (c == '\f') || (c == '\v')) {
      if (c == '\n') GetWordLineNo++;
      Word[CharsRead]='\0';
      *WordLength=CharsRead;
      return(Word);
    }
    if(c == EOF){
      Word[CharsRead]='\0';
      *WordLength=CharsRead;
      *eofptr = 1;
      return(Word);
    }
    if(CharsRead == (Available-1)){ /* -1 because of null */
      Available += INITLENGTH/2;
      Word = (char *) realloc( (void *) Word, (size_t) (Available * sizeof (char)));
      if(Word == NULL) return(Word);
    }
    Word[CharsRead++]= (char) c;
  }
}