c - 在c中获取文件参数

标签 c

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

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);

最佳答案

通过 stat() 函数:

手册:man 2 stat

原型(prototype):

   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 */
   };

关于c - 在c中获取文件参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14292536/

相关文章:

python - C 数据结构

c - 在套接字上设置超时不起作用

c - 如何声明全局结构数组并在不同的函数中使用它?

c - 如何使用双指针找到二维数组中列的长度?

c - 如何将单元测试添加到已建立的(自动工具)C 项目中

c - 来自 sk_buff 的 IP 地址

c++ - 错误: operator '&&' has no right operand

c - Doxygen 不为全局函数生成文档

c++ - 用 C 处理 TCP 的部分返回

C - 将 int 从十六进制转换为十进制?