所以我试图从命令行解析命令,如:
cd /mnt/cdrom
来
#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
}
就我所做的而言,我不确定如何在没有字符串函数的情况下拆分它。
答案 0 :(得分:0)
嗯,它在急速解决方案中,但它的工作原理..当然你需要动态分配内存在parse函数中,例如某种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;
}