2013-12-13 61 views
0

我想執行到shell find命令來打印我只* .c文件 然後返回字符串與文件並將其打印到標準輸出。 我正在使用管道來做到這一點。當我嘗試跑我總是得到find failed: No such file or directoryexecl()查找命令c

我認爲問題是路徑。 我應該給它的路徑是home/username/Downloads如果我想打印我的Downloads文件夾中存在的所有* .c文件?

#include <stdio.h> 
#include <stdlib.h> 


int main(int argc, char ** argv){ 
    int fds[2]; 
    char buffer[4096]; 

    if(pipe(fds) == -1){ 
     perror("pipe creation failed"); 
     exit(1); 
    } 

    switch (fork()){ 

    case 0://child 
     close(fds[0]); 
     execl("usr/bin/find","find","home/username/Downloads", "-name \"*.c\" -print0",NULL); 
     perror("find failed"); 
     exit(20); 
     break; 

     case -1: //fork failure 
     perror("fork failure"); 
     exit(1); 

     default: //parent 
     close(fds[1]); //close stdin so only can do stdout 
     int size= read(fds[0],buffer, 4096); 
     printf("%s",buffer); 
    } 

    exit(1); 
} 
+0

argv [0]是程序名稱而不是程序的第一個參數 – doctorlove

+0

好的你是對的。我現在編輯 – Antifa

+0

你應該使用glob()函數。另請參閱readdir()或stat() – Sevauk

回答

1

我建議通過單獨的參數作爲單獨的參數:

execl("/usr/bin/find", "find", 
     "/home/username/Downloads", 
     "-name", 
     "*.c", /* As no shell is invoked no quotation marks are needed to protect the *. */ 
     "-print0", 
     (char *) NULL); 
+0

你能幫我打印結果嗎? – Antifa

2

有在USR前面缺少一個斜線/斌/發現,所以只找到被執行時的工作目錄是/

+0

你是對的! 並打印結果?我該怎麼辦? – Antifa

+0

使用dup()或dup2()重定向find的stdout – Sevauk