linux系统编程之stat函数

1.查看一个文件的信息

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

int main(int argc,char*argv[])
{
  if(argc!=2)
  {
     printf("./a.out filename\n");
     return -1;
  }
  struct stat sb;
  stat(argv[1],&sb);
  return 0;
}

2.实现ls -l filed的功能

需要使用 struct passwd *getpwuid(uid_t uid);获得用户名 需要传入uid

struct passwf{
char * pw_name;
char *pw_passwd;
uid_t pw_uid;
gid_t pw_gid;
char * pw_gecos;
char *pw_dir;
char * pw_shell;
}

struct group*getgrgid(gid_t gid);获得组名
struct group{
char * gr_name;
char *gr_passwd;
gid_t gr_gid;
char ** gr_mem;
}

获得本地时间
struct tm*localtime(const time_t *timep)
传入参数:timep 对应stat函数得到的结构体的秒数
返回tm结构体

struct tm{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;//月+1
int tm_year;//年+1900
int tm_wday;
int tm_yday;
int tm_isdst;
}

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<time.h>
#include<pwd.h>
#include<grp.h>

int main(int argc,char *argv[])
(
  if(argc!=2)
  {
    printf("./a.out filename\n");
    return -1;
  }
  //调用stat 得到文件属性信息
  struct stat sb;
  stat(argv[1],&sb);
  //解析属性信息  st_mode.uid .gid.time
  char stmode[10]={0};
  memset(stmode,'-',sizeof(stmode));
  
  if(S_ISREG(sb.st_mode))
   stmode[0]='-';
    if(S_ISDIR(sb.st_mode))
   stmode[0]='d';
    if(S_ISCHR(sb.st_mode))
   stmode[0]='c';
    if(S_ISBLK(sb.st_mode))
   stmode[0]='b';
    if(S_ISFIFO(sb.st_mode))
   stmode[0]='p';
    if(S_ISLIK(sb.st_mode))
   stmode[0]='l';
    if(S_ISSOCK(sb.st_mode))
   stmode[0]='s';

  //解析权限
  if(sb.st_mode&S_IRUSR)
   stmode[1]='r';
  if(sb.st_mode&S_IWRUSR)
   stmode[2]='w'; 
  if(sb.st_mode&S_IXUSR)
   stmode[3]='x';
  
  if(sb.st_mode&S_IRGRP)
   stmode[4]='r';
  if(sb.st_mode&S_IWGRP)
   stmode[5]='w'; 
  if(sb.st_mode&S_IXGRP)
   stmode[6]='x';
  if(sb.st_mode&S_IROTH)
   stmode[7]='r';
  if(sb.st_mode&S_IWOTH)
   stmode[8]='w'; 
  if(sb.st_mode&S_IXOTH)
   stmode[9]='x';
  
  //分析 用户名 组名通过函数获得 
  
  struct tm*filetm=localtime(&sb,st_atim.tv_sec);
  char timebuf[20]={0};
  sprintf(timebuf,"%d月  %d %02d:%02d",filetm->tm_mon+1,filetm->tm_mday,filetm->tm_hour,filetm->tm_min);
  printf("%s %1  d %s %s %1d %s %s\n",stmode,sb.st_nlink,getpwupid(sb.st_uid)->pw_name,getgrgid(sb.st_gid)->gr_name,sb.st_size,argv[1]);
  return 0;
)

注意:stat和lstat 的区别
stat 碰到连接,会追述到源文件,穿透!!!lstat 并不会穿透

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值