#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void ini(char*, char*);
int main(int args, char* argv[])
{
if(args!=3) {printf("Enter correct format: myls.out . an"); return 0;}
ini(argv[1],argv[2]);
return 0;
}
void ini(char* dir,char* match)
{
DIR* dirp;
dirp = opendir(dir);
if (dirp == NULL)
{
printf("\ndir open error\n");
exit(1);
} //Error for opening dir
else
{
struct stat fst;
struct dirent* dentry;
dentry = readdir(dirp);
while (dentry != NULL)
{
if (!stat(dentry->d_name, &fst))
{
// report as whether is a directory or regular file
if (S_ISDIR(fst.st_mode))
{
if(!strcmp(dentry->d_name,".") || !strcmp(dentry->d_name,".."));
else
{
char fullpath[1024];
strcpy(fullpath,dir);
strcat(fullpath,"/");
strcat(fullpath,dentry->d_name);
ini(fullpath,match);
}
}
else if (S_ISREG(fst.st_mode))
{
if(strstr(dentry->d_name,match)!=NULL)
printf("%s/%s \n",dir,dentry->d_name);
}
}
dentry = readdir(dirp);
}
closedir(dirp);
}
printf("\n");
}
該程序需要2個參數。示例運行:爲什麼這個遞歸搜索不能進入第二級?
./a.out . an
./andy.txt
./subdir/band.out
./subdir/cs337/handy.c
./than.text
當參數名稱是文件名稱的子字符串時,顯示完整路徑和文件的名稱。我的代碼的問題是它只能向下一級。誰能幫我? 樣品:
./a.out . an
./andy.txt
./subdir/band.out
./than.text
的問題是'STAT(dentry-> d_name, &fst)'只是傳遞一個沒有完整路徑名的文件名。所以如果它不在當前目錄中,它會失敗。 – lurker