Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running wc(word count) command in C

I am trying to run wc linux command from a C program but I am not getting the desired output.

int main() {

    pid_t pid = fork();
    
    if (pid == -1) {
        perror("Error forking process");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {

        int fid = open("testtxt.txt", O_RDONLY);
        if (fid == -1) {
            perror("Error opening file");
            exit(EXIT_FAILURE);
        }
        
        close(0);
        dup2(fid, STDIN_FILENO);
        close(fid);
        
        execlp("wc", "wc", (char *)NULL);
        
    } else {
        wait(NULL);
    }

    return 0;
}

As per my understanding I am creating a child process using fork() and in the pid==0 else if block I am setting the stdin for the child process as texttxt.txt file. Then I am using execlp to run the wc command on the file. And as the stdout is still the terminal it should print the word count of the provided file on the terminal. I have wait(NULL) in the else clause to stop the parent process during the execution of child process.

But the output I get on terminal is not what I expect.
The output I get is 1 14 78

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone please explain me where I am going wrong?

>Solution :

You do not test for execlp() failure, which is very likely as its first argument must point to an executable file… but you are probably not running your program from the /usr/bin directory that contains the wc program. Change the line to

      execlp("/usr/bin/wc", "wc", (char *)NULL);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading