所以我试图从命令行解析命令,例如:
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/