我试图标记用户输入的Shell程序命令。该程序可以运行,但是我认为它不会填充我声明的参数数组。很抱歉,在我学习过程中似乎没有很多信息,但是我不确定为什么它没有填充参数。任何帮助将不胜感激,如果您需要任何其他信息,请随时询问。
#include "HeaderFile.h"
#include <stdio.h>
#include <stdlib.h>
#define token_delimiter " \n\r"
char **shell_read(char *line, char **param){
line = NULL;
ssize_t size = 0;
getline(&line, &size, stdin);
//printf("%s", line);
int i = 0;
char *line_token;
line_token = strtok(line, token_delimiter);
printf("%s", line_token);
for(i=1; line_token!=NULL; i++){
param[i] = line_token;
line_token = strtok(NULL, token_delimiter);
}
param[0] = NULL;
return(param);
}
最佳答案
像这样的东西:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define token_delimiter " \n\r"
char **shell_read(void){//Parameters are not necessary. because they are made in this function.
char *line = NULL;
size_t size = 0;
ssize_t len;
if(-1 == (len = getline(&line, &size, stdin))){
free(line);
return NULL;
}
char **param = malloc(sizeof(*param) * ((len + 1)/2 + 1));//last +1 for NULL
int i = 0;
char *line_token = strtok(line, token_delimiter);
while(line_token != NULL){
param[i++] = strdup(line_token);//need allocate and copy
line_token = strtok(NULL, token_delimiter);
}
param[i] = NULL;
free(line);
return param;
}
int main(void){
putchar('>');fflush(stdout);
char **tokens = shell_read();
if(tokens){
for(char **token = tokens; *token; ++token){
puts(*token);
free(*token);
}
free(tokens);
}
return 0;
}