如何判断文件还是子目录?

ArchiLife 2011-01-14 11:00:51
使用readdir进行目录遍历后,返回的是dirent结构体,



struct dirent {
__ulong64_t d_offset; /* real off after this entry */
ino_t d_ino; /* inode number of entry */
ushort_t d_reclen; /* length of this record */
ushort_t d_namlen; /* length of string in d_name */
char d_name[_D_NAME_MAX+1]; /* name must be no longer than this */
/* redefine w/#define when name decided */
};



我想区别哪些是文件,哪些是子目录,难道我需要一个一个opendir去尝试么?
...全文
195 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
ArchiLife 2011-01-14
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 bluejays 的回复:]
刚才少贴了两行
S_ISLNK(m)
symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m)
socket? (Not in POSIX.1-1996.)
http://www.linuxmanpages.com/man2/lstat.2.php#
[/Quote]

呵呵,源代码看到了,是分了两处。看来内核设计的时候也是后面补上去的。
justkk 2011-01-14
  • 打赏
  • 举报
回复
软链接本身就是链接,不是普通文件,也不是目录
S_ISLNK
bluejays 2011-01-14
  • 打赏
  • 举报
回复
刚才少贴了两行
S_ISLNK(m)
symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m)
socket? (Not in POSIX.1-1996.)
http://www.linuxmanpages.com/man2/lstat.2.php#
ArchiLife 2011-01-14
  • 打赏
  • 举报
回复
对lstat还是有点疑惑,因为一个软链接有可能指向一个目录,也有可能指向一个文件。

判断类型的5个宏里面没有包括软链接,那么,软链接本身算是一个regular file还是一个directory?
bluejays 2011-01-14
  • 打赏
  • 举报
回复
The following POSIX macros are defined to check the file type:

S_ISREG(m)
is it a regular file?
S_ISDIR(m)
directory?
S_ISCHR(m)
character device?
S_ISBLK(m)
block device?
S_ISFIFO(m)
fifo?
bluejays 2011-01-14
  • 打赏
  • 举报
回复
DIR *dp;
struct dirent *entry;
struct stat statbuf;

while ((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode))
{ 是子目录}
justkk 2011-01-14
  • 打赏
  • 举报
回复
struct stat a;
stat(d_name, &a);
if( S_ISDIR(a.st_mode) ) 目录;
bluejays 2011-01-14
  • 打赏
  • 举报
回复
用lstat判断

23,110

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧