【问题标题】:Reading from Standard Input and storing each word in a separate column of an array [duplicate]从标准输入读取并将每个单词存储在数组的单独列中[重复]
【发布时间】:2021-07-21 12:10:54
【问题描述】:

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

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

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

fgets(buffer, BUF_SIZE, stdin);

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

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

有人可以告诉我如何按该顺序将命令保存在命令数组中吗?

【问题讨论】:

  • 使用 strtok 函数对输入进行标记
  • 是的,分离输入。但是当我尝试使用execvp() 时,我收到了这个警告:warning: passing argument 1 of ‘execvp’ makes pointer from integer without a cast [-Wint-conversion] execvp(commands[0],commands);

标签: c execvp


【解决方案1】:

试试这段代码:

    #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;
}

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多