gpt4 book ai didi

c - stat 函数不适用于子目录?

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:48 25 4
gpt4 key购买 nike

我正在尝试递归读取目录并打印出有关文件的一些元数据。我有针对单个目录的程序。但是对于子目录,当我应用 stat 方法时,文件不断给出不存在这样的文件或目录的错误。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

void scan( const char *dir) // process one directory
{
DIR *dp;
struct dirent *de;
struct stat sbuf;

dp = opendir( dir);
if( dp == NULL)
{
// perror( dir);
printf("Cannot open directory %s\n",dir);
return;
}

while( 1)
{
const char * d_name;
de = readdir( dp);
if( de == NULL)
break;//Empty Directory

d_name = de->d_name;
printf("d_name: %s\n",d_name);
// if(strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0)
// printf("%s/%s\n",dir,d_name);//Print File or Directory


if( stat( de->d_name, &sbuf) )
{
// perror( de->d_name);
printf("Error in stat %s\n",de->d_name);
continue;
}

if( S_ISDIR(sbuf.st_mode) && (strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0))
{
// printf("d_name: %s\n",d_name);
printf( "d\t");
}
else
if (strcmp(d_name,"..") == 0 || strcmp(d_name,".") == 0)
{
// printf("d_name: %s\n",d_name);
// continue;
}
else
{
// printf("d_name tab: %s\n",d_name);
printf( "\t");
}

if(strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0)
printf( "%lu\t%s\n", (unsigned long) sbuf.st_size, de->d_name);

if(de->d_type == DT_DIR)
{
if(strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0)
{
char path[1024];
snprintf(path,1024,"%s/%s",dir,d_name);
scan(path);

}
}

}

closedir( dp);
}

int main( int argc, char *argv[])
{
int i;
scan(argv[1]);

return 0;
}

最佳答案

stating 时,您忘记将您的dir 添加到您的de->d_name 中。您仍在原来的目录中,因为您还没有在其他地方chdired。

关于c - stat 函数不适用于子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23284075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com