简体   繁体   中英

Parsing a command line command without string library

So i am trying to parse a command from a command line like:

cd /mnt/cdrom

comes to

  • 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
}

That is as far as i have made it im not really sure how to split it at this point without string functions.

Well it's in haste solution, but it works.. Of course you need to dynamically allocate memory in parse function with some kind of list for example (for different arguments) and some kind of buffer for current argument processing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM