-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathescape.c
54 lines (50 loc) · 920 Bytes
/
escape.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "escape.h"
struct buffer {
char *ptr;
size_t len;
size_t cap;
};
static void buf_putc(struct buffer *buf, char c)
{
if (buf->ptr == NULL) {
buf->cap = 32;
buf->ptr = malloc(buf->cap);
buf->len = 0;
if (buf->ptr == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
}
if (buf->len == buf->cap) {
buf->cap *= 2;
buf->ptr = realloc(buf->ptr, buf->cap);
}
buf->ptr[buf->len++] = c;
}
char *escape(char **argv)
{
struct buffer b = { 0 };
for (; *argv; ++argv) {
char *arg = *argv;
for (; *arg; ++arg) {
char c = *arg;
switch (c) {
case ' ':
case '\\':
case '\'':
case '\"':
buf_putc(&b, '\\');
break;
default:
break;
}
buf_putc(&b, c);
}
if (*(argv + 1))
buf_putc(&b, ' ');
}
return b.ptr;
}