Question

I have the following code:

int main(void) {
    char in[100];
    printf("> ");
    fgets(in, sizeof(in), stdin);
    int pid;
    char *f[100];
    char *v;
    int i = 1;
    v = strtok(in, " ");
    f[0] = v;
    while (v = strtok(NULL, " ")){
        f[i] = v;
        i++;
    }
    f[i] = NULL;
    execvp(f[0], f);
    perror("FAILED");
    exit(1);
}

For some reason, anytime I enter in something like "ls -l" or "date", it tells me no such file or directory. When I wrote in the code:

f[0] = "ls";
f[1] = "-l";
f[2] = NULL;

it worked fine. Any ideas?

Was it helpful?

Solution

There is a small mistake in your code. This is about the usage of the fgets function. When you use fgets the whole given as input along with the new line character is taken into the character string v. Just add the following two lines after fgets function and your code works fine.

int size = strlen(in);
in[size-1] = '\0';

This is just to remove the new line character from the string.

So when you press ls -l[ENTER]. ls is taken in the first word f[0] and -l'\n' is taken in f[1] and the execvp is not able to find and executable with ls -l'\n'

OTHER TIPS

try:

char* str;
str = strtok(inputBuffer," \n");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top