我是第一次使用目录,遇到了一些困难。我编写了以下函数来浏览目录、显示文件大小和权限,然后递归访问任何子目录。
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() 真的是探索子目录的最佳方式吗?
谢谢
最佳答案
当你打开一个子目录./snails
时,你会使用readdir()
从目录中读取文件名,比如chewy-snails
,但对于 stat()
文件,您需要在名称前加上子目录名称:./snails/chewy-snails
。
另一种方法(不要掉以轻心)是考虑使用 chdir()
或(更好的)fchdir()
将目录更改为相关的子目录。然后,您可以 stat()
来自 readdir()
的名称,而不会弄乱字符串。但是,回到起点是个问题——尤其是当您按照符号链接(symbolic link)到达那里时。这是fchdir()
的地方分数。
如果您使用的系统具有必要的支持,*at()
函数可能会有所帮助(fstatat()
等)。
但最简单的解决方案是在尝试使用 stat()
之前不更改目录并在文件名前加上子目录名前缀或者
lstat()
— 这是同一内容的 3 个链接。
关于c - C 的新手,使用目录 : Trouble opening files within subdirectories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18776559/