【问题标题】:Parsing a command line command without string library解析没有字符串库的命令行命令
【发布时间】:2015-02-13 02:37:13
【问题描述】:

所以我试图从命令行解析一个命令,例如:

cd /mnt/cdrom

来到

  • name = "cd"
  • argc = 2
  • argv = {"cd", "/mnt/cdrom", NULL}

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
void parse(char* line, command_t* command) {

    // TODO: Check if string is empty or null
        while (line[i] != ' ' && line[i] != '\0')
     i++;

     if (line[i] == ' ') {

         }

    // TODO: Split the string on whitespace -> should become an array of char
    // TODO: The first string is the command, the length of tokens[1:] is the length of the arguments, and tokens[1:] are the arguments
    // TODO: Create/fill-in the command struct with the data from above
}

就我所做的而言,我不确定在没有字符串函数的情况下如何在这一点上拆分它。

【问题讨论】:

  • 1) 为什么没有string.h? 2)你到底想解析什么?如果您的命令行类似于my cd /mnt/cdrom,或者甚至带有空格my cd "/home/my directory",您将收到正确的参数argv[0] = my, argv[1] = cd, argv[2] = /home/my directory。
  • 对不起,我不清楚我正在制作自己的 shell,我需要解析用户输入的命令。

标签: c


【解决方案1】:

好吧,这是一种仓促的解决方案,但它确实有效。当然,您需要在解析函数中动态分配内存,例如使用某种list(用于不同的参数)和某种用于当前参数处理的缓冲区。

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

#define MAX_TOKEN  5
#define MAX_LENGTH 64

void copy_str( char* dst, char* src, int size ) {
    int i = 0;
    for( i = 0; i < size; ++i ) {
        dst[i] = src[i];
    }
}

char** parse( char* line, int size, int* argc ) {
    int i = 0, j = 0;
    char** argv = NULL;
    argv = (char**)calloc( MAX_TOKEN, sizeof(char*) );
    for( i = 0; i < MAX_TOKEN; ++i ) {
        argv[i] = (char*)calloc( MAX_LENGTH, sizeof(char) );
    }
    for( i = 0; i < size; ++i ) {
        if( line[i] == ' ' ) {
            copy_str( argv[*argc], line + j, i - j );
            j = i + 1; // length of token
            (*argc)++;
        }
    }
    // copy last
    copy_str( argv[*argc], line + j, i - j );
    (*argc)++;
    return argv;
}

int main( ) {
    int t = 0, i;
    char* s = "cd /mnt/cdrom";
    char** argv = parse( s, 13, &t );
    for( i = 0; i < t; ++i ) {
        printf( "%s\n", argv[i] );
    }
    t = 0;
    s = "ls -l /home/";
    argv = parse( s, 12, &t );
    for( i = 0; i < t; ++i ) {
        printf( "%s\n", argv[i] );
    }
    return 0;
}

【讨论】:

  • 动态分配内存可以用malloc吗?
  • 是的,我使用calloc 只是为了用零填充分配的内存。
  • 那么如果我使用 malloc 会发生什么变化呢? argv = (char**)malloc(sizeof(char*));
  • 如果您想使用malloc,请将, 更改为*,例如argv = (char**)malloc( MAX_TOKEN * sizeof(char*) );
猜你喜欢
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
  • 2014-12-27
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多