tags:

views:

63

answers:

2

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

+3  A: 

Why not use the wc (word count) program? Just pipe your output to wc -w and you're done.

WoLpH
+2  A: 

Your word count program is always using argv[1] as the input file. If you want to support reading from stdin or a given file, then you would need to change what you use for your input based on the number of arguments given to your program.

std::streambuf* buf;
std::ifstream infile;
if (argc > 1)
{
    // Received an argument, so use it as a source file
    infile.open(argv[1]);
    if (!infile)
    {
        perror("open");
        return 1;
    }
    buf = infile.rdbuf();
}
else
{
    // No arguments so use stdin
    buf = std::cin.rdbuf();
}

std::istream input(buf);
while (!input.eof())
{
    ...
}
...
jamessan