解析 C 中的命令行条目:实现 shell



我正在用 C 实现一个 shell,我在解析命令行条目时遇到了一些问题。我希望我的解析器方法分隔由空格字符分隔的命令行条目,并将结果作为双字符指针返回。即,假设我有"ls -l>ls.txt",我的解析器应该返回一个带有 r[0]="ls"、r[1]="-l"和 r[2]=">ls.txt"的字符 **r。

这是我当前解析方法的代码,顺便说一下,它是段错误,我对如何解决这个问题一无所知:

 char **parser(int *argc, char *s)
 {
     char **r;
     char *t, *m;
     int i,n,size;
     t = malloc(strlen(s)); // firs i used this instead of *r, but i run 
                            // into trouble when i have more than two
                            // argc. ( You see why, right?)
    //strcpy(t,s);
    i = 0;
    size = 5;
    r = malloc(size*sizeof(char *));
    while (( m = strchr(s, ' '))) {
        n = ((int)m) - ((int)s);
        if (i==0) {
          *r = malloc(n);
        } else {
           *r = realloc(*r, n);
        }
        strncpy(*r, s, n);
        *r[n]= '';
        s = (char*)(s+n+1);
        if (i == size)
            r = realloc(r, (size = 2*size)*sizeof(char*));
        i++;
        r = (char **)(r + sizeof(char*));
   }
   s[strlen(s)-1] = '';
   if ((i<1) || (strlen(s)>1)) {
       *r = s;
   }
   *argcp = ++i;
   return r;
}

我知道我的代码并不理想。使用 strsep 可以做得更好,但我的主要问题是如何管理我要返回的双字符指针的内存。

感谢您的帮助!

这是一个

快速的刺。

我的 C 生锈了,所有的铰链都卡住了,所以。

前提是你最终会得到一个指向指针数组的指针。不过,在该指针列表的末尾,关键细节是参数数据本身。因此,完成后,只需释放返回的指针即可。

未经测试。这里很可能有一个一次性的错误潜入。

编辑,我编译并快速测试了它。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char **parser(int *argc, char *s) {
    char **r, **rp;
    char *t, *p, *w;
    void *vp;
    int l;
    l = strlen(s); // size of cmd line
    vp = malloc(l + (*argc * sizeof(char *))); // total buffer size
    t = (char *)(vp + (*argc * sizeof(char *))); // offset into buffer for argument copy
    r = (char **)vp;  // start of buffer, start of pointer array to arguments
    strcpy(t, s);  // copy arguments in to buffer
    p = t;  // parsing pointer
    w = t;  // word pointer for each argument
    rp = r;  // storage for first pointer
    while(*p) {  // while not at end of string
        if (*p == ' ') {  // if we find a space
            if (w) {  // if we have a word pointer assigned
                *rp++ = w;  // store the word pointer
                w = NULL;  // set word pointer to null
                *p = '';  // terminate argument with a 0
            } // else do nothing continue to skip spaces
        } else {
            if (w == NULL) {  // If we haven't got a new arg yet
                w = p;  // set it
            }  // otherwise, just keep scanning
        }
        p++;  // move along the string
    }
    if (w) {  // clean up at the end if we have an arg
        *rp++ = w;
        w = NULL;  // no reason to set 0 at the end, it's already there from strcpy
    }
    return r;
}
int main() {
    char *cmd = "arg1 arg2";
    int argc = 2;
    char **r = parser(&argc, cmd);
    printf("%sn",r[0]);
    printf("%sn",r[1]);
}

最新更新