Joe*_*man 3 c c++ systems-programming
我想检查文件是目录,链接还是仅仅是常规文件.我遍历目录并将每个文件保存为struct dirent *
.我试图传递d_ino
给S_ISDIR(m)
,, S_ISLINK(m)
或者S_ISREG(m)
无论文件如何,我都不会得到积极的结果.所以我的问题是:我怎么使用S_ISDIR(m)
带struct dirent
?
使用时读取目录时readdir(3)
,文件类型存储在您收到d_type
的每个成员变量中struct dirent
,而不是d_ino
成员中.您很少会关心inode编号.
但是,并非所有实现都具有该d_type
成员的有效数据,因此您可能需要调用stat(3)
或lstat(3)
在每个文件上确定其文件类型(lstat
如果您对符号链接感兴趣,请使用,或者stat
如果您对目标感兴趣,请使用符号链接)然后st_mode
使用S_IS***
宏检查成员.
典型的目录迭代可能如下所示:
// Error checking omitted for expository purposes
DIR *dir = opendir(dir_to_read);
struct dirent *entry;
while((entry = readdir(dir)) != NULL)
{
struct stat st;
char filename[512];
snprintf(filename, sizeof(filename), "%s/%s", dir_to_read, entry->d_name);
lstat(filename, &st);
if(S_ISDIR(st.st_mode))
{
// This directory entry is another directory
}
else if(S_ISLINK(st.st_mode))
{
// This entry is a symbolic link
}
else if(S_ISREG(st.st_mode))
{
// This entry is a regular file
}
// etc.
}
closedir(dir);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10911 次 |
最近记录: |