2016-01-07 25 views
-1

我正在嘗試在C中編寫一個程序來搜索某個文件中的單詞 請問您可以幫我嗎?如何在函數中使用grep?

#include<unistd.h> 
#include<sys/types.h> 
#include<stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include <string.h> 
#include <time.h> 

int main() 
{ 
    int pid; 
    //string s; 
    //s = grep(); 
    pid = fork(); 
    if(pid < 0) 
    { 
     printf("Failed"); 
     exit(-1); 
    } 

    else if (pid == 0) 
    { 
     printf("Child id %d\n",getpid()); 
     execlp("/bin/bzexe","grep the", NULL); 
    } 

    else 
    { 
     wait(NULL); 
     printf("Parent id %d |\n ",getpid()); 
     exit(0); 
    } 
return 0; 
} 
+1

什麼是'bzexe'? – Barmar

+0

這是一個文件... – Emad

回答

0

當您調用execlp時,該命令的參數必須是該函數的單獨參數。因此,它應該是:

execlp("/bin/bzexe", "grep", "the", (char*)NULL); 

你也應該投的NULL參數(char*),因爲NULL宏不一定擴大爲指針類型,和可變參數一樣execlp功能不會自動轉換爲指針類型。

+0

我會嘗試。非常感謝。 – Emad

+0

它沒有工作。它只給了我孩子ID和家長ID。 – Emad

+0

由於您沒有爲'grep'提供文件名參數,因此它將處理標準輸入。如果你將程序的輸入重定向到一個文件,它將顯示所有匹配'the'的行。 – Barmar