我注意到我的函数输出(在c中)有些奇怪。此功能在目录中检测元素是文件还是子目录。
// i cant detected properly if an element is a file or a dir
int RecursiveSearch(char *Dir){
DIR *Directory;
//DIR *SubDirectory;
struct dirent *entry;
struct stat filestat;
printf("I am Reading %s Directory\n", Dir);
Directory = opendir(Dir);
if(Directory == NULL)
{
perror("Unable to read directory.. i'm leaving\n");
return(1); // leave
}
/* Read directory entries */
while( (entry=readdir(Directory)) )
{
stat(entry->d_name,&filestat);
if( S_ISDIR(filestat.st_mode) ){
printf("%4s: %s\n","Dir",entry->d_name);
if (strstr(entry->d_name, ".") == NULL && strstr(entry->d_name, "..") == NULL ) // to not infinit loop
{
// Recursion
printf("\n*Entering a subDirectory*\n");
RecursiveSearch(entry->d_name);
printf("\n*Leaving a subDirectory*\n");
}
}
else
printf("%4s: %s\n","File",entry->d_name);
}
closedir(Directory);
return(0);
}
我这样称呼它来测试它RecursiveSearch("./Directories");
我的问题在“开始递归研究..”下]
您可以看到SubDir不是文件。我看不到我在功能中做错了。
如果需要任何其他说明,请询问。
编辑:
int RecursiveSearch(char *Dir){
DIR *Directory;
struct dirent *entry;
struct stat filestat;
printf("I am Reading %s Directory\n", Dir);
Directory = opendir(Dir);
if(Directory == NULL)
{
perror("Unable to read directory.. i'm leaving\n");
return(1); // leave
}
/* Read directory entries */
while( (entry=readdir(Directory)) )
{
char fullname[100];
sprintf(fullname, "%s/%s",Dir,entry->d_name);
stat(fullname,&filestat);
if( S_ISDIR(filestat.st_mode) ){
printf("%4s: %s\n","Dir",fullname);
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 ) // to not infinite loop
{
// Recursion
printf("\n*Entering a subDirectory*\n");
RecursiveSearch(fullname);
printf("\n*Leaving a subDirectory*\n");
}
}
else
printf("%4s: %s\n","File",fullname);
}
closedir(Directory);
return(0);
}
我注意到我的函数输出(在c中)有些奇怪。此功能在目录中检测元素是文件还是子目录。 //如果元素是文件,我无法正确检测到...
entry->d_name
仅是名称,没有目录前缀。它是相对于进程的工作目录而不是函数递归中的当前目录来解释的。