stat函数不适用于子目录?

时间:2014-04-25 04:18:16

标签: c unix

我试图递归地读取目录并打印出一些有关文件的元数据。我有单个目录的程序工作。但是对于子目录,当我应用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;
}

1 个答案:

答案 0 :(得分:2)

dir时,您忘记将de->d_name添加到stat前。您仍然在原始目录中,因为您没有chdir在其他位置。