#include #include #include #define IS_SPECIAL(c) (c == ' ' ? 1 : \ c == '&' ? 1 : \ c == '<' ? 1 : \ c == '|' ? 1 : \ c == '"' ? 1 : 0) static char * escape_quoting(const char* arg) { char dq_on, seen_bs; char *ptr, *ret, *ret_ptr; /* New(1310, ret, strlen(ptr) + 1, char); */ ret = (char*) malloc(strlen(ptr) + 1); ret_ptr = ret; for(dq_on = 0, seen_bs = 0, ptr = (char*)arg; *ptr != '\0'; ptr++) { if('\\' == *ptr && 0 == seen_bs) { seen_bs = 1; continue; } if('\\' == *ptr && 1 == seen_bs) seen_bs = 0; if('"' == *ptr && 0 == seen_bs && 0 == dq_on) { dq_on = 1; continue; } if(1 == dq_on && IS_SPECIAL(*ptr)) { if(*(ptr + 1) != '\0' && '"' == *(ptr + 1)) *ret_ptr++ = *ptr++; dq_on = 0; continue; } *ret_ptr++ = *ptr; dq_on = seen_bs = 0; } *ret_ptr = '\0'; return ret; } int main(void) { char arg1[] = "print\"\"\"foo\" \"bar\"\"\""; char arg2[] = "print\"\"\"\"foo bar\"\"\"\""; char arg3[] = "\"print\\\"foo bar\\\""; char arg4[] = "\"print\\\"foo bar\\\"\""; char arg5[] = "print\\\"foo\" \"bar\\\""; char arg6[] = "print'\"\"\"\"\"\"\"\"'"; char arg7[] = "\"print \\\"\\\\\\\"\\\\\\\"\\\""; char *quoted; quoted = escape_quoting(arg1); printf("%s\n", quoted); free(quoted); quoted = escape_quoting(arg2); printf("%s\n", quoted); free(quoted); quoted = escape_quoting(arg3); printf("%s\n", quoted); free(quoted); quoted = escape_quoting(arg4); printf("%s\n", quoted); free(quoted); quoted = escape_quoting(arg5); printf("%s\n", quoted); free(quoted); quoted = escape_quoting(arg6); printf("%s\n", quoted); free(quoted); quoted = escape_quoting(arg7); printf("%s\n", quoted); free(quoted); return 0; }