how to implement word count bash shell

Posted by codemax on Stack Overflow See other posts from Stack Overflow or by codemax
Published on 2010-04-16T16:45:18Z Indexed on 2010/04/16 16:53 UTC
Read the original article Hit count: 359

Filed under:

hey guys.
I am trying to write my own code for the word count in bash shell.
I did usual way. But i wanna use pipe's output to count the word.
So for eg the 1st command is cat and i am redirecting to a file called med.
Now i have to use to 'dup2' function to count the words in that file. How can i write the code for my wc?

This is the code for my shell pgm :

void process( char* cmd[], int arg_count )  
{    
    pid_t pid;  
    pid = fork();   
    char path[81];  
    getcwd(path,81);  
    strcat(path,"/");  
    strcat(path,cmd[0]);  
    if(pid < 0)  
    {  
        cout << "Fork Failed" << endl;  
        exit(-1);  
    }  
    else if( pid == 0 )  
    {  
        int fd;  
        fd =open("med",  O_RDONLY);  
        dup2(fd ,0);  
          execvp( path, cmd );  
    }  
        else  
        {  
        wait(NULL);  
    }  
}  

And my wordcount is :

int main(int argc, char *argv[])  
{  
    char ch;  
    int count = 0;  
    ifstream infile(argv[1]);  
    while(!infile.eof())  
    {  
        infile.get(ch);  
        if(ch == ' ')  
        {  
            count++;  
        }  
    }  
    return 0;  
}  

I dont know how to do input redirection i want my code to do this : When i just type wordcount in my shell implementation, I want it to count the words in the med file by default. Thanks in advance

© Stack Overflow or respective owner

Related posts about shell