2013-12-13 57 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