c 解析命令行实现

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值