I want to take a command with its options as input and execute it with one of the exec() functions.

My approach is to take input first and put it in an array by dividing with string tokenizer. Then I call execvp() which takes the array including the command as parameter.
When I try my code with input "ls -l", I get the error below.

ls: invalid option -- '

I tried with different exec() functions just giving second element of array and giving path myself as "/bin/ls". But I can't make it work. There is a problem with the "-l" part.

Could you guys give me an advice? Thank you.

My code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h> 

int main(){

    char input[30];
    char* args[10];
    char argIndex = 0;
    printf("Enter command or program name: ");
    char* str;
    str = strtok(input, " ");
    while(str != NULL){
        args[argIndex] = str;
        str = strtok(NULL, " ");
   args[argIndex] = (char *) 0;

   execvp(args[0], args);


You need to strip the newline off the end - did you notice the line break in the invalid option?

Try str = strtok(NULL, " \n");

Thank you very much. I couldn't notice this fault, if you didn't tell. Now it works as I wanted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.