How to use stat(),fstat(),lstat() in Unix ?

19 篇文章 0 订阅
/*
  This program can tell you the type of the files given .
  struct stat include the information of the file.

*****************struct 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 filesystem I/O
    blkcnt_t  st_blocks;   number of 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
};
******************************************************

we use some macros to test the type of the file
*****************************macros*******************
    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 (named pipe)?
    S_ISLNK(m)
        symbolic link? (Not in POSIX.1-1996.)
    S_ISSOCK(m)
        socket? (Not in POSIX.1-1996.)
******************************************************

There are three functions given you can use.
******************************************************
int stat(const char *restrict pathname, struct stat *restrict buff);
int fstat(int filedes, struct stat *restrict buff);
int lstat(const char *restrict pathname, struct stat *restrict buff);
******************************************************


*/

#include <stdio.h>
#include <sys/stat.h>

int main(int argc,char **argv)
{
  struct stat buff;
  int i = 0;
  for(i = 1;i < argc;i++)
  {

    printf("%s:",argv[i]);

    if(lstat(argv[i],&buff) < 0)
    {
      printf("lsata error!!\n");
      continue;
    }

    if(S_ISREG(buff.st_mode))
      printf("regular file\n");
    else if(S_ISDIR(buff.st_mode))
      printf("Directory file\n");
    else if(S_ISCHR(buff.st_mode))
      printf("character special\n");
    else if(S_ISBLK(buff.st_mode))
      printf("Block special\n");
    else if(S_ISFIFO(buff.st_mode))
      printf("FIFO file\n");
    else if(S_ISLNK(buff.st_mode))
      printf("Link file\n");
    else if(S_ISSOCK(buff.st_mode))
      printf("socket file\n");
  }

  return 1;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值