从标准输入读取并将每个单词存储在数组的单独列中

问题描述

假设我有一个缓冲区和其他一些用于存储标准输入的指针:

char buffer[256];
char *command[3];

我正在从标准输入读取到缓冲区:

fgets(buffer,BUF_SIZE,stdin);

如果标准输入是 ls -s1,我想要 command[0]="ls"command[1]="-s1"。我也想要command[2]=NULL

对于上下文,我稍后会尝试使用 execvp(),因此我希望所有命令都以 command 分隔,并在末尾使用空字符。

有人能告诉我如何按顺序保存命令数组中的命令吗?

解决方法

试试这段代码:

    #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
int main() {
    
    char buffer[256];
    char *command[3];
    int i=0;

    fgets(buffer,256,stdin);
    char *p = strchr(buffer,'\n');
    if (p)  *p = 0;
    char *token=strtok(buffer," ");
    command[0]=strdup(token);
    printf("%s\n",command[0] );
    while(token!=NULL){
        
        token=strtok(NULL," ");
        if(token!=NULL){

            command[++i]=strdup(token);
            printf("%s\n",command[i]);
        }
    }
    command[2]=NULL;
    execvp(command[0],command);
    return 0;
}