我试图以递归方式打开目录并打印一些有关文件的元数据。但是,目录无法打开。目录名称是正确的,我很难说为什么opendir不工作。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.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;
}
// printf("%s\n",dir);
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(de->d_name,"..") == 0 || strcmp(de->d_name,".") == 0)
continue;
//AT THIS POINT ALL .. AND . SHOULD BE SKIPPED AND CONTINUED.
char abs_path[1024];
snprintf(abs_path,1024,"%s/%s",dir,de->d_name);
if(stat(abs_path, &sbuf))
{
//perror(abs_path);
printf("Error in stat %s\n",abs_path);
continue;
}
if( S_ISDIR(sbuf.st_mode))
{
printf( "d\t");
printf( "%lu\t%s\n", (unsigned long) sbuf.st_size,abs_path);
scan(abs_path);
}
else
{
//printf("d_name tab: %s\n",d_name);
printf("\t");
printf( "%lu\t%s\n", (unsigned long) sbuf.st_size,abs_path);
}
}
closedir(dp);
}
int main( int argc, char *argv[])
{
if( argc > 1)
for( int i = 1; i < argc; ++i)
scan( argv[i]);
else
scan(".");
return 0;
}