2013-05-07 165 views
1

我有一个读取单个输入目录中包含的所有文件的函数。
我想让该函数不仅读取“main”目录中的文件,而且还读取所有子目录中包含的文件。C - 列出文件夹和所有子文件夹中包含的文件

为了做到这一点,我写了这个代码:

#include <sys/types.h> 
#include <dirent.h> 
#include <errno.h> 
#include <stdio.h> 

struct dirent *readdir(DIR *dirp); 
char * percorso; 
DIR *cartella; 
struct dirent *elemento; 



char * scrivi(char * a, char * b) 
{ 

char *targetdir = malloc(2048); 
strcpy(targetdir,a); 
strcat(targetdir,"/"); 
strcat(targetdir,b); 

printf("%s \n", targetdir); 
return targetdir; 
}  

void scorriFolder(char* nome) 
{ 
if ((cartella = opendir(nome)) == NULL)   
    perror("opendir() error");      
else { 
    printf("contents of root: \n"); 
    while ((elemento = readdir(cartella)) != NULL) 
    {            
     if(elemento->d_type == DT_DIR) 
     { 
      if(elemento->d_name != ".." || elemento->d_name != ".") 
      { 
       percorso = scrivi(nome, elemento->d_name); 
       scorriFolder(percorso); 
      } 
     } 
     else 
     { 
      printf(" %s\n", elemento->d_name); 
     } 
    } 
    closedir(cartella);       
} 
}  

main(int argc, char * argv[]) { 
scorriFolder(argv[1]); 
} 

但它甚至不进行编译,说:

warning: incompatible implicit declaration of built-in function ‘malloc’ 
warning: incompatible implicit declaration of built-in function ‘strcpy’ 
warning: incompatible implicit declaration of built-in function ‘strcat’ 

据我所知,这个问题是由于传递给mallocstrcpystrcat函数的错误格式的变量。 (elemento->d_name具有类型char而不是char*

我能做些什么,以获得此代码的工作

感谢

编辑

这是一个工作while片段:?

while ((elemento = readdir(cartella)) != NULL) 

{    
     if (strcmp(elemento->d_name, ".") == 0) 
     { 
      continue; 
     } 
     if (strcmp(elemento->d_name, "..") == 0) 
     { 
      continue; 
     } 
      if(elemento->d_type == DT_DIR) 
      { 

       { 
        percorso = scrivi(nome, elemento->d_name); 
        scorriFolder(percorso); 
       } 
      } 
      else 
      { 
       printf(" %s\n", elemento->d_name); 
      } 
     } 

一旦它sc ans一个子目录崩溃,因为程序从子目录中退出时路径不会更新。我正在修复它。

+2

'定义为找出这些函数的定义,你可以阅读man page elemento-> d_name!=“..”'使用strcmp – BLUEPIXY 2013-05-07 21:13:38

+0

我已经完成了。现在还有另一个问题,但我试图自己修复它。如果我失败,我会再次问这里:D – 2013-05-07 21:28:45

+0

如果你在UNIX系统上查看'fts()'和过时的'ftw()'函数。因为他们在遍历文件层次结构方面做了很多工作。 – 2013-05-07 21:36:07

回答

5

您需要将#include <stdlib.h>#include <string.h>添加到文件的开头。

warning: incompatible implicit declaration of built-in function ‘malloc’ 

此错误消息告诉您编译器不能确定返回类型和参数malloc。我认为如果找不到一个返回类型,编译器就会假设int为int。哪个不是malloc实际返回的void *

的malloc在<stdlib.h>

的strcpy和strcat的定义在<string.h>

通过键入man mallocman strcpy,或man strcat

相关问题