2010-04-16 23 views
0

我想在bash shell中編寫我自己的字數統計代碼。
我做了平常的方法。但是我想用管道的輸出來統計這個詞。
因此,例如第一個命令是貓,我正在重定向到一個名爲med的文件。
現在我必須使用'dup2'函數來計算該文件中的單詞。我怎樣才能爲我的wc編寫代碼?如何實現字數bash 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); 
    } 
} 

我的單詞計數是:

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; 
} 

我不知道該怎麼做輸入重定向 我希望我的代碼來做到這一點: 當我只在我的shell實現中輸入wordcount時,我希望它在默認情況下計算med文件中的單詞。 在此先感謝

+1

這聽起來像是家庭作業。考慮添加「家庭作業」標籤。 – 2010-04-16 17:14:26

回答

4

爲什麼不使用wc(字數)程序?只需將您的輸出輸出到wc -w即可完成。

2

您的字數統計程序始終使用argv[1]作爲輸入文件。如果您想支持從stdin或給定文件讀取數據,則需要根據提供給您的程序的參數數量來更改用於輸入的內容。

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()) 
{ 
    ... 
} 
...