c - 解析没有字符串库的命令行命令

标签 c

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

cd /mnt/cdrom

来到

  • 名称=“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
}

据我所知,我不太确定此时如何在没有字符串函数的情况下分割它。

最佳答案

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

    #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;
}

关于c - 解析没有字符串库的命令行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28482990/

相关文章:

c - 可执行文件的文本输出部分显示在控制台上

c - 多次包含的头文件中的 Typedef

c - 尝试以持续时间和频率发出蜂鸣声时出现 ioctl 错误

c - 将程序与两个静态库链接,每个静态库都包含依赖于另一个函数的函数?

c++ - 当编译器决定填充结构时

c - 为什么 C 中的运算符 sizeof( function ) 输出 1 个字节

c - 从特定时区获取日期 - C

不使用预定义方法进行转换

c++ - ffmpeg 在 libavutil 中缺少 config.h(没有这样的文件或目录)CodeBlocks

c - C 编译器如何为位域定义的结构分配结构内存?