forked from ec429/3psk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrbuf.c
93 lines (86 loc) · 1.28 KB
/
strbuf.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
3psk - 3-pole Phase Shift Keying
Copyright (c) Edward Cree, 2012
Licensed under the GNU GPL v3+
strbuf: auto-reallocating string buffers
*/
#include <stdlib.h>
#include "strbuf.h"
void append_char(char **buf, size_t *l, size_t *i, char c)
{
if(*buf)
{
(*buf)[(*i)++]=c;
}
else
{
init_char(buf, l, i);
append_char(buf, l, i, c);
}
char *nbuf=*buf;
if((*i)>=(*l))
{
*l=*i*2;
nbuf=realloc(*buf, *l);
}
if(nbuf)
{
*buf=nbuf;
(*buf)[*i]=0;
}
else
{
free(*buf);
init_char(buf, l, i);
}
}
void append_str(char **buf, size_t *l, size_t *i, const char *str)
{
while(str && *str) // not the most tremendously efficient implementation, but conceptually simple at least
{
append_char(buf, l, i, *str++);
}
}
void init_char(char **buf, size_t *l, size_t *i)
{
*l=80;
*buf=malloc(*l);
(*buf)[0]=0;
*i=0;
}
char * fgetl(FILE *fp)
{
char * lout;
size_t l,i;
init_char(&lout, &l, &i);
signed int c;
while(!feof(fp))
{
c=fgetc(fp);
if((c==EOF)||(c=='\n'))
break;
if(c!=0)
{
append_char(&lout, &l, &i, c);
}
}
return(lout);
}
char *slurp(FILE *fp)
{
char *fout;
size_t l,i;
init_char(&fout, &l, &i);
signed int c;
while(!feof(fp))
{
c=fgetc(fp);
if(c==EOF)
break;
if(c!=0)
{
append_char(&fout, &l, &i, c);
}
}
return(fout);
}