Guy
Guy

Reputation: 115

->Running wc command using execv

I am trying to create a simple function that counts lines from a text file and print it by using Unix command wc (word count). I don't understand why it does not work; I tried different paths for wc location but nothing works.

Instead, I get this error:

�%r  : No such file or directory

I want to use the wc command.

Code:

void count_lines() {
    int p;
    p=fork();
    if(p == 0) {
        char* args[] = {"./wc","1.txt",NULL};
        execv("./wc",args);
        perror(execv);
        exit(0);
    }

    printf("waiting for child\n");
    wait(NULL);
    }

Upvotes: 0

Views: 4520

Answers (2)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

You need to correct below two lines in your code. Always provide full path to the file location. In case of unsuccessful command execution, you need to check access permission to the file location including permission to execute the file or command:-

char* args[]={"wc","-l","/full/path/1.txt",NULL};
execv("/usr/bin/wc",args);

Normally all unix/Linux commands should be in directory location /usr/bin/. To get the full path for a command just try like below:-

which command #here command can be wc, ls etc. so try which wc

Upvotes: 2

P.P
P.P

Reputation: 121407

Unless you have an binary in your current directory, ./wc is not going to work. Since you want to use the wc command, use the path to it:

int p;
p=fork();

if(p == 0) {
    char* args[] = {"wc","1.txt",NULL};
    execv("/usr/bin/wc",args);
    perror("execv");
    exit(0);
}

Or you could use execvp to let it search wc in PATH:

int p;
p=fork();

if(p == 0) {
    char* args[] = {"wc","1.txt",NULL};
    execvp("wc",args);
    perror("execvp");
    exit(0);
}

Upvotes: 3

Related Questions