0

Lets say I have a buffer and some other pointer for storing the stdin:

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

And I'm reading from stdin into buffer:

fgets(buffer, BUF_SIZE, stdin);

If stdin was ls -s1, I want to have command[0]="ls" and command[1]="-s1". I also want command[2]=NULL.

For context I am trying to use execvp() later on so I want all the commands separated in command with the null character at the end.

Could someone please let me know how could I go about saving the commands in the command array in that order?

  • 1
    use strtok function to tokenize the input – nissim abehcera Apr 28 '21 at 06:55
  • Yes, with the separating the input. but when I try to use `execvp()`, I get this warning: `warning: passing argument 1 of ‘execvp’ makes pointer from integer without a cast [-Wint-conversion] execvp(commands[0],commands);` – Borna Morassaei Apr 28 '21 at 07:15
  • See [How to use execvp](https://stackoverflow.com/questions/27541910/how-to-use-execvp) – gkhaos Apr 28 '21 at 07:34

1 Answers1

0

Try this piece of code :

    #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;
}
nissim abehcera
  • 821
  • 6
  • 7