0

我有这个递归函数来搜索文件的树结构。我需要找出每个文件的参数(类型,所有者,组,权限,创建日期,最后修改日期,..)怎么做?

void search(const char * path)
{
  char newpath[PATH_SIZE + 1];

  DIR * dp;
  struct dirent * ep;

  dp = opendir(path);
  if (dp == NULL)
    return;

  while ((ep = readdir(dp)) != NULL)
  {
    if (strcmp(".",  ep->d_name) == 0 ||
        strcmp("..", ep->d_name) == 0)
    {
      continue;
    }

    printf("%s/%s\n", path, ep->d_name);


    if ((ep->d_type & DT_DIR) == DT_DIR)
    {
      if (strlen(path) + strlen(ep->d_name) + 1 <= PATH_SIZE)
      {
        sprintf(newpath, "%s/%s", path, ep->d_name);
        search(newpath);
      }
    }
  }

  closedir(dp);

  return;
}

我只知道文件的类型(ep-> d_type);

4

2 回答 2

1

通过 stat() 函数:

手动的:man 2 stat

原型:

   int stat(const char *path, struct stat *buf);
   int fstat(int fd, struct stat *buf);
   int lstat(const char *path, struct stat *buf);

其中 stat 结构定义为:

   struct stat {
       dev_t     st_dev;     /* ID of device containing file */
       ino_t     st_ino;     /* inode number */
       mode_t    st_mode;    /* protection */
       nlink_t   st_nlink;   /* number of hard links */
       uid_t     st_uid;     /* user ID of owner */
       gid_t     st_gid;     /* group ID of owner */
       dev_t     st_rdev;    /* device ID (if special file) */
       off_t     st_size;    /* total size, in bytes */
       blksize_t st_blksize; /* blocksize for file system I/O */
       blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
       time_t    st_atime;   /* time of last access */
       time_t    st_mtime;   /* time of last modification */
       time_t    st_ctime;   /* time of last status change */
   };
于 2013-01-12T10:48:47.983 回答
1

@gustaf r 给出的答案是绝对正确的。但是,我想再添加 1 点,您也可以在 MAN 页面中找到。

These functions return information about a file.   No  permissions  are
   required  on  the  file itself, but—in the case of stat() and lstat() —
   execute (search) permission is required on all of  the  directories  in
   path that lead to the file.

因此,您正在处理的目录应该具有适当的权限。

于 2013-01-12T10:54:17.990 回答