传入一个文件,显示文件详细信息

来源:互联网 发布:php开发和java开发 编辑:程序博客网 时间:2024/05/20 18:41
#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <stdlib.h>#include <time.h>#include <grp.h>#include <pwd.h>//传入一个文件,显示文件详细信息//-rwxrwxrwx 1 root root      1723 Nov 30 09:49 27_lstat.c//权限    链接数 所有者 用户组 文件容量 修改日期 文件名//文件所有者权限 文件所属用户组的权限 其他人对此文件的权限#if 0struct 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 所有者ID*/               gid_t     st_gid;     /* group ID of owner 用户组ID*/               dev_t     st_rdev;    /* device ID (if special file) */               off_t     st_size;    /* total size, in bytes 文件容量*/               blksize_t st_blksize; /* blocksize for file system I/O */               blkcnt_t  st_blocks;  /* number of 512B 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 修改日期*/           };#endif#if 0    struct group *getgrgid(gid_t gid);struct group {               char   *gr_name;       /* group name */               char   *gr_passwd;     /* group password */               gid_t   gr_gid;        /* group ID */               char  **gr_mem;        /* group members */           };#endifint main(int argc,char *argv[]){    struct stat buf;    if(lstat(argv[1],&buf) < 0)//lstat获取文件信息    {        perror("lstat failed");//需要加""        exit(1);    }    //打印文件类型    if(S_ISREG(buf.st_mode))        printf("-");    if(S_ISDIR(buf.st_mode))        printf("d");    if(S_ISCHR(buf.st_mode))        printf("c");    if(S_ISBLK(buf.st_mode))        printf("b");    if(S_ISFIFO(buf.st_mode))        printf("p");    if(S_ISLNK(buf.st_mode))        printf("l");    if(S_ISSOCK(buf.st_mode))        printf("s");    //打印文件权限    -rwxrwxrwx 421421421     char str[] = "xwr-";    int i;    for(i=8;i>0;i--)    {        if(buf.st_mode & 1 << i)//左移            printf("%c",str[i%3]);        else             printf("%c",str[3]);    }    //打印文件链接数    printf(" %d ",buf.st_nlink);    //打印文件所有者    printf("%s ",getpwuid(buf.st_uid)->pw_name);//    //打印文件用户组    printf("%s ",getgrgid(buf.st_gid)->gr_name);    //打印文件容量    printf("%ld ",buf.st_size);    //打印修改日期    struct tm *tp;    tp = localtime(&buf.st_ctime);//    printf("%d-%d-%d %d:%d:%d\n",tp->tm_year+1900, tp->tm_mon+1, \                        tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec);    //打印文件名    printf("-----filename is %s-----\n",argv[1]);    return 0;}
原创粉丝点击