stat命令的学习与C语言实现

stat命令的学习

man stat

STAT(1)                          User Commands                         STAT(1)

NAME
       stat - display file or file system status

SYNOPSIS
       stat [OPTION]... FILE...

DESCRIPTION
       Display file or file system status.

       Mandatory  arguments  to  long  options are mandatory for short options
       too.

       -L, --dereference
              follow links

       -f, --file-system
              display file system status instead of file status

       -c  --format=FORMAT
              use the specified FORMAT instead of the default; output  a  new‐
              line after each use of FORMAT

       --printf=FORMAT
              like  --format, but interpret backslash escapes, and do not out‐
              put a mandatory trailing newline; if you want a newline, include
              \n in FORMAT

       -t, --terse
              print the information in terse form

       --help display this help and exit

       --version
              output version information and exit

       The valid format sequences for files (without --file-system):

       %a     access rights in octal (note '#' and '0' printf flags)

       %A     access rights in human readable form

       %b     number of blocks allocated (see %B)

       %B     the size in bytes of each block reported by %b

       %C     SELinux security context string

       %d     device number in decimal

       %D     device number in hex

       %f     raw mode in hex

       %F     file type

       %g     group ID of owner

       %G     group name of owner

       %h     number of hard links

       %i     inode number

       %m     mount point

       %n     file name

       %N     quoted file name with dereference if symbolic link

       %o     optimal I/O transfer size hint

       %s     total size, in bytes

       %t     major  device  type  in  hex, for character/block device special
              files

       %T     minor device type in hex,  for  character/block  device  special
              files

       %u     user ID of owner

       %U     user name of owner

       %w     time of file birth, human-readable; - if unknown

       %W     time of file birth, seconds since Epoch; 0 if unknown

       %x     time of last access, human-readable

       %X     time of last access, seconds since Epoch

       %y     time of last data modification, human-readable

       %Y     time of last data modification, seconds since Epoch

       %z     time of last status change, human-readable

       %Z     time of last status change, seconds since Epoch

       Valid format sequences for file systems:

       %a     free blocks available to non-superuser

       %b     total data blocks in file system

       %c     total file nodes in file system

       %d     free file nodes in file system

       %f     free blocks in file system

       %i     file system ID in hex

       %l     maximum length of filenames

       %n     file name

       %s     block size (for faster transfers)

       %S     fundamental block size (for block counts)

       %t     file system type in hex

       %T     file system type in human readable form

   --terse is equivalent to the following FORMAT:
              %n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %W %o %C

   --terse --file-system is equivalent to the following FORMAT:
              %n %i %l %t %s %S %b %f %a %c %d

       NOTE: your shell may have its own version of stat, which usually super‐
       sedes the version described here.  Please refer to your  shell's  docu‐
       mentation for details about the options it supports.

AUTHOR
       Written by Michael Meskes.

REPORTING BUGS
       GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
       Report stat translation bugs to <https://translationproject.org/team/>

COPYRIGHT
       Copyright  ©  2018  Free Software Foundation, Inc.  License GPLv3+: GNU
       GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
       This is free software: you are free  to  change  and  redistribute  it.
       There is NO WARRANTY, to the extent permitted by law.


stat命令参数

-L, --dereference 跟随链接
-f, --file-system 显示文件系统状态而非文件状态
-c --format=FORMAT use the specified FORMAT instead of the default;
output a newline after each use of FORMAT
--printf=FORMAT like --format, but interpret backslash escapes,
and do not output a mandatory trailing newline;
if you want a newline, include \n in FORMAT
-t, --terse print the information in terse form
--help 显示此帮助信息并退出
--version 显示版本信息并退出

stat函数结构体

           struct stat {
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */
               mode_t    st_mode;        /* File type and mode */
               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;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */
            }

产品代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <string.h>
#include <time.h>
#include <sys/timeb.h>

struct stat sb;
struct tm *lt;
struct tm stm;
time_t t;

void timeswitch(struct tm *lt)
{
	char nowtime[24];
	memset(nowtime, 0, sizeof(nowtime));
	strftime(nowtime, 24, "%Y-%m-%d %H:%M:%S", lt);
	printf("%s\n", nowtime);
}

int main(int argc, char *argv[])
{
    int n;
    struct passwd *pwd;
    // = getpwuid(sb.st_uid);
    char nowtime[24];
    int count[3]={0};
    int cou = 0;
    int flag = 0;
    char mode[8]={0};
    if (argc != 2) 
    {
        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if (lstat(argv[1], &sb) == -1) 
    {
        perror("lstat");
        exit(EXIT_FAILURE);
    }

    printf("  文件: %s\n",argv[1]);
    printf("  大小:  %lld bytes       ",(long long) sb.st_size);
    printf("块: %lld        ",(long long) sb.st_blocks);
    printf("I/O 块: %ld    ",(long) sb.st_blksize);

    switch (sb.st_mode & S_IFMT) 
    {
        case S_IFBLK:  printf("块设备\n");            break;
        case S_IFCHR:  printf("字符设备\n");        break;
        case S_IFDIR:  printf("目录\n");       flag=1;        break;
        case S_IFIFO:  printf("FIFO/管道\n");               break;
        case S_IFLNK:  printf("symlink\n");                 break;
        case S_IFREG:  printf("普通文件\n");            break;
        case S_IFSOCK: printf("socket\n");                  break;
        default:       printf("unknown?\n");                break;
    }
    printf("设备:%ld                ",(long)sb.st_dev);
    printf("Inode: %ld     ", (long) sb.st_ino);
    printf("硬链接: %ld\n", (long) sb.st_nlink);
    printf("权限:");
    printf("(");
  
    for(n=8;n>=0;n--)
	{
		if(sb.st_mode&(1<<n))
		{
			switch(n%3)
			{
			case 2:
                mode[8-n] = 'r';
                count[n/3] += 4;
				break;
			case 1:
                mode[8-n] = 'w';
                count[n/3] += 2;
				break;
			case 0:
				mode[8-n] = 'x';
                count[n/3] += 1;
                break;
			default:
				break;
			}
		}
		else
		{
            mode[8-n] = '-';
        }
	}
    printf("0%d%d%d/",count[2],count[1],count[0]);
    
    if(flag)
    {
        printf("d");
    }
    else
    {
        printf("-");
    }
    for ( cou = 0; cou <= 8; cou++)
    {
        printf("%c",mode[cou]);
    }
    printf(")  ");
    pwd = getpwuid(sb.st_uid);
    printf("UID: ( %ld/   %s)   GID: ( %ld/    %s )\n",(long) sb.st_uid,pwd->pw_name, (long) sb.st_gid,pwd->pw_name);

    printf("最近访问:  "); 
    timeswitch(localtime(&sb.st_atime));

    printf("最近更改:  "); 
    timeswitch(localtime(&sb.st_ctime));

    printf("最近改动:  "); 
    timeswitch(localtime(&sb.st_mtime));

    printf("创建时间:  -\n"); 
    exit(EXIT_SUCCESS);
}

码云链接

对比截图:

posted @ 2021-11-05 19:58  Bzrael  阅读(335)  评论(0编辑  收藏  举报