我正在尝试将用户的inputed命令标记为shell程序。该程序运行但我认为它没有填充我声明的param数组。我很抱歉,如果我似乎没有大量的信息,因为我正在学习这样做,但我不确定为什么它没有填补参数。任何帮助将不胜感激,如果您需要任何其他信息,请随时询问。
#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);
}
答案 0 :(得分:-1)
类似的东西:
#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;
}