我有一个函数可以读取单个输入目录中包含的所有文件。
我想让该函数不仅读取“主”目录中的文件,还读取所有子目录中包含的文件。
为了做到这一点,我写了这段代码:
#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’
据我所知,这个问题是由于传递给malloc
、strcpy
和strcat
函数的变量格式错误所致。 (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);
}
}
一旦它扫描到一个子目录,它就会崩溃,因为当程序从子目录退出时,它的路径没有更新。我正在尝试修复它。
最佳答案
您需要添加 #include <stdlib.h>
和 #include <string.h>
到文件的开头。
warning: incompatible implicit declaration of built-in function ‘malloc’
此错误消息告诉您编译器无法确定 malloc
的返回类型和参数.我认为如果找不到返回类型,编译器会假定返回类型为 int。哪个不是 void *
哪个 malloc 实际返回。
malloc 在 <stdlib.h>
中定义
strcpy 和 strcat 在 <string.h>
中定义
要找出这些函数的定义位置,您可以通过键入 man malloc
来阅读手册页。 , man strcpy
, 或 man strcat
关于C - 列出文件夹和所有子文件夹中包含的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16428370/