我想在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文件中的單詞。 在此先感謝
這聽起來像是家庭作業。考慮添加「家庭作業」標籤。 – 2010-04-16 17:14:26