gpt4 book ai didi

c - 在c中获取文件参数

转载 作者:行者123 更新时间:2023-11-30 14:21:55 26 4
gpt4 key购买 nike

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

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/

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