我第一次使用目录并且遇到了一些困难。我编写了以下函数来探索目录,显示文件大小和权限,然后递归任何子目录。
void exploreDIR (DIR* dir, char cwd[], int tab)
{
struct dirent* ent;
while ((ent = readdir(dir)) != NULL)
{
if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
int i;
i = 0;
while(i < tab)
{
printf(" ");
i = i + 1;
}
printf("%s ", ent->d_name);
FILE *file = fopen(ent->d_name, "r");
int filesize;
if(file==NULL)
{
printf("[ Could not open! ]\n");
continue;
}
struct stat st;
stat(ent->d_name, &st);
filesize = st.st_size;
if (st.st_mode & S_IFDIR)
{
printf ("(subdirectory) [");
}
else
{
printf("(%d bytes) [", filesize);
}
printf( (S_ISDIR(st.st_mode)) ? "d" : "-");
printf( (st.st_mode & S_IRUSR) ? "r" : "-");
printf( (st.st_mode & S_IWUSR) ? "w" : "-");
printf( (st.st_mode & S_IXUSR) ? "x" : "-");
printf( (st.st_mode & S_IRGRP) ? "r" : "-");
printf( (st.st_mode & S_IWGRP) ? "w" : "-");
printf( (st.st_mode & S_IXGRP) ? "x" : "-");
printf( (st.st_mode & S_IROTH) ? "r" : "-");
printf( (st.st_mode & S_IWOTH) ? "w" : "-");
printf( (st.st_mode & S_IXOTH) ? "x" : "-");
printf("]\n");
fclose(file);
if (st.st_mode & S_IFDIR)
{
char tempwd[1024];
strcpy(tempwd, cwd);
strcat(tempwd, "/");
strcat(tempwd, ent->d_name);
DIR* tempdir;
if ((tempdir = opendir (tempwd)) != NULL)
{
printf("%s", tempwd);
exploreDIR(tempdir, tempwd, tab + 1);
}
}
}
closedir(dir);
}
但是,当函数在子目录上递归时,fopen 函数总是返回 null。我这辈子都想不通。作为参考,这是主要的:
int main(int argc, char** argv)
{
printf("\n");
DIR* dir;
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL)
{
if ((dir = opendir (cwd)) != NULL)
{
exploreDIR(dir, cwd, 0);
}
}
printf("\n");
return (EXIT_SUCCESS);
}
我也有点担心我的方法论。strcat() 真的是探索子目录的最佳方式吗?
谢谢