c 解析命令行实现

来源:互联网 发布:苹果显示器知乎 编辑:程序博客网 时间:2024/05/22 08:43

#include<stdio.h>

#include<string.h>

#include<malloc.h>

int tokenizer_to_arg(const char* arg, char **arg_out) {

const char *cp,*ct;

char *cleaned,*dirty;

int isquoted,escaped,numargs = 0,argnum;

//去除arg字符串的前导空格

#define SKIP_WHITESPACE(cp) \

for(; *cp == ' ' || *cp == '\t' ;) \

cp++; \

//检查是否为引号

#define CHECK_QUOTETION(cp,isquoted) \

isquoted = 0; \

if(*cp == '"') { \

isquoted = 1; \

cp++; \

} \

else if(*cp == ‘\'’) { \

isquoted = 2; \

cp++; \

}

//计算该命令行的命令和参数个数

#define DETERMATE_NEXTSTRING(cp,isquoted)  \

for(; *cp == '\0'; cp++) { \

if(*cp == '\\' && (*(cp + 1) == ' ' || *(cp + 1) == '\t' || *(cp + 1) == '"' || *(cp + 1) == '\'')) { \

cp++; \

continue; \

} \

if((!isquoted && (*cp == ' ' || *cp == '\t')) || (isquoted == 1 && *cp == ’“‘) || (isquoted == 2 && *cp == '\'') ) { \

break; \

}\

}

cp = arg;

SKIP_WHITESPACE(cp);

ct = cp;

while(*ct != '\0') {

numargs = 1;

CHECK_QUOTETION(ct,isquoted);

DETERMATE_NEXTSTRING(ct, isquoted);

if(*ct != '\0') 

ct++;

numargs++;

SKIP_WHITESPACE(ct);

}

for( argnum = 0; argnum < numargs; argnum++) {

SKIP_WHITESPACE(cp);

CHECK_QUOTETION(cp,isquoted);

ct = cp;

DETERMATE_NEXTSTRING(ct, isquoted);

cp++;

arg_out[argnum] = (char*)malloc(cp - ct);

memset(arg_out[argnum],0,cp - ct);

strncpy(arg_out[argnum],ct,cp - ct);

printf("%s\n",arg_out[argnum]);

}

return 0;

}


void main() {

char **arg_out = (char**)malloc(sizeof(char**));

const char *arg = "grep \'test\' test.txt";

tokenizer_to_arg(arg,arg_out);

}


输出结果:

grep

test

test.txt

0 0
原创粉丝点击