-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_wrapper.c
65 lines (53 loc) · 1.21 KB
/
string_wrapper.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
char *getStr();
int main() {
printf("Type long string to fold\n");
char *str = getStr();
int foldingLen = 10, idx = 10;
int j = 0, len = strlen(str), tmpLen = len / foldingLen;
char *tmp = (char *) malloc((tmpLen + len) * sizeof(char));
for(int i = 0; i < len; i++, j++) {
tmp[j] = str[i];
if(i == foldingLen) {
if(str[i] != ' '){
foldingLen++;
continue;
}
j++;
tmp[j] = '\n';
foldingLen = foldingLen + idx;
}
}
printf("%s \n", tmp);
free(tmp);
}
char *getStr()
{
char *str = NULL, *tmp = NULL;
size_t size = 0, index = 0;
int ch = EOF;
int CHUNK = 1;
while (ch) {
ch = getc(stdin);
/* Check if we need to stop. */
if (ch == EOF || ch == '\n')
ch = 0;
/* Check if we need to expand. */
if (size <= index) {
size += CHUNK;
tmp = realloc(str, size);
if (!tmp) {
free(str);
str = NULL;
break;
}
str = tmp;
}
/* Actually store the thing. */
str[index++] = ch;
}
return str;
}