Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5705160
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类: C/C++

2007-10-28 19:49:28

    今天李超在邮件列表里面问道了如何实现isdir的函数,我给他回来一个使用stat获得状态,再根据st_mode来判断是不是目录,后来又想到使用opendir来通过判断返回值来判断是不是目录。

    下面的代码中有三种实现方式,其中opendir有两种,其中一个是宏实现。

代码:
wangyao@fisherman:~/pinggu/exp2/half_open$ cat t_isdir.c
#include
#include
#include
#include

#define ISDIR(path) opendir(path)==NULL?0:1

int isdir_opendir(const char *path)
{
        if( opendir(path) )
                return 1;
        else
                return 0;
}

int isdir_lstat(char *path)
{
        struct stat buf;

        if( lstat(path,&buf) != 0)
        {
                perror("lstat error");
                return 0;
        }

        if( S_ISDIR(buf.st_mode) )
                return 1;
        else
                return 0;
}

int main(int argc,char *argv[])
{
        int temp;

        temp = ISDIR(argv[1]);
        /*
        temp = isdir_opendir(argv[1]);
        temp = isdir_lstat(argv[1]);
        */
        if(temp)
                printf("%s is DIR.\n",argv[1]);
        else
                printf("%s is not DIR.\n",argv[1]);

        return 0;
}


阅读(1941) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~