1 /*
2  * Copyright (c) Tony Bybell 1999-2013.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  */
9 
10 #include "globals.h"
11 #include <config.h>
12 #include <string.h>
13 #include <ctype.h>
14 #include "fgetdynamic.h"
15 #include "debug.h"
16 
17 
fgetmalloc(FILE * handle)18 char *fgetmalloc(FILE *handle)
19 {
20 struct vlist_t *v;
21 char *pnt = NULL;
22 int i, ch;
23 
24 v = vlist_create(sizeof(char));
25 
26 do
27 	{
28 	for(;;)
29 		{
30 		ch=fgetc(handle);
31 		if((ch==EOF)||(ch==0x00)||(ch=='\n')||(ch=='\r')) break;
32 
33 		pnt = (char *)vlist_alloc(&v, 0);
34 		*pnt = (char)ch;
35 		}
36 	} while(!pnt && ((ch=='\n')||(ch=='\r'))); /* fix for \n\r on \n systems */
37 
38 GLOBALS->fgetmalloc_len = vlist_size(v);
39 
40 if(!GLOBALS->fgetmalloc_len)
41 	{
42 	pnt = NULL;
43 	}
44 	else
45 	{
46 	pnt=malloc_2(GLOBALS->fgetmalloc_len+1);
47 	for(i=0;i<GLOBALS->fgetmalloc_len;i++)
48 		{
49 		pnt[i] = *((char *)vlist_locate(v, i));
50 		}
51 	pnt[i] = 0;
52 	}
53 
54 vlist_destroy(v);
55 return(pnt);
56 }
57 
58 
59 /*
60  * remove any leading and trailing spaces
61  */
stripspaces(char * s)62 static char *stripspaces(char *s)
63 {
64 int len;
65 
66 if(s)
67 	{
68 	char *s2 = s + strlen(s) - 1;
69 	while(isspace((int)(unsigned char)*s2) && (s2 != s)) { *s2 = 0; s2--; }
70 
71 	s2 = s;
72 	while(*s2 && isspace((int)(unsigned char)*s2)) { s2++; }
73 
74 	if((len = strlen(s2)))
75 		{
76 		char *s3 = malloc_2(len + 1);
77 		strcpy(s3, s2);
78 		free_2(s);
79 		s = s3;
80 
81 		GLOBALS->fgetmalloc_len = len;
82 		}
83 		else
84 		{
85 		free_2(s); s = NULL;
86 		GLOBALS->fgetmalloc_len = 0;
87 		}
88 	}
89 
90 return(s);
91 }
92 
93 
fgetmalloc_stripspaces(FILE * handle)94 char *fgetmalloc_stripspaces(FILE *handle)
95 {
96 char *s = fgetmalloc(handle);
97 return(stripspaces(s));
98 }
99 
100 
101 /*
102  * variants for tcl argument passing which really aren't fgetdynamic-ish functions...
103  * the struct wave_script_args * passed in was generated in tcl_helper.c.
104  */
wave_script_args_fgetmalloc(struct wave_script_args * w)105 char *wave_script_args_fgetmalloc(struct wave_script_args *w)
106 {
107 char *pnt;
108 
109 if((!w)||(!w->curr)) return(NULL);
110 
111 pnt = malloc_2(strlen(w->curr->payload)+1);
112 strcpy(pnt, w->curr->payload);
113 
114 w->curr = w->curr->next;
115 return(pnt);
116 }
117 
118 
wave_script_args_fgetmalloc_stripspaces(struct wave_script_args * w)119 char *wave_script_args_fgetmalloc_stripspaces(struct wave_script_args *w)
120 {
121 char *s = wave_script_args_fgetmalloc(w);
122 return(stripspaces(s));
123 }
124 
125