stat命令的实现-mysate

学习stat(1)

解决方法

禁用 man 的 SECCOMP

export MAN_DISABLE_SECCOMP=1

永久解决:修改用户目录下的~/.bashrc文件进行配置

vim ~/.bashrc

在最后一行加上

export MAN_DISABLE_SECCOMP=1

:wq 保存退出

关于stat

作用:获取文件信息
头文件:include <sys/types.h> #include <sys/stat.h> #include <unistd.h>
函数原型:int stat(const char *path, struct stat *buf)
返回值:成功返回0,失败返回-1;
参数:文件路径(名),struct stat 类型的结构体

man -k ,grep -r的使用

man -k:根据关键字搜索联机帮助

grep -r :快速搜索在目录下面的含有关键字的文件

man -k stat

grep -r status

在编写代码的过程中,会遇到很多不知道的类型和宏定义,需要使用grep -r xx /usr/include

例如发现有一个变量:st_size不清楚其类型意义。使用grep -r st_size /usr/include查询

man -k stat | grep 2

伪代码

  1. 判断输入中是否包含文件参数,如果有则继续,没有则提示用户输入错误

  2. 声明结构体,并调用stat()函数给结构体赋值

  3. 逐个取出结构体中的数据并输出即可

    • 依次打印输出节点ino
    • 文件类型mode
    • 文件的连接数nlink
    • 用户ID uid和组ID gid
    • 块大小blksize
    • 字节数size
    • 块数目blocks
    • 三个时间atime、mtime和ctime
  4. 注意文件的mode需要switch来判断

产品代码 mystate.c

查看stat()的结构体

man 2 stat

函数原型:int stat(const char *path, struct stat *buf)

  • path:指定文件
  • buf:buf是一个传出参数,也就是一级指针做输出,我们应该先定义一个结构体变量,并把该变量取地址&传给形参。

#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    struct stat sb;
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s &lt;pathname&gt;\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if (stat(argv[1],&sb) == -1)
    {
        perror("stat");
        exit(EXIT_FAILURE);
    }
    printf("File type:                ");
    switch (sb.st_mode&S_IFMT)
    {
    case S_IFBLK:
        printf("block device\n");
        break;
    case S_IFCHR:
        printf("character device\n");
        break;
    case S_IFDIR:
        printf("directory\n");
        break;
    case S_IFIFO:
        printf("FIFO/pipe\n");
        break;
    case S_IFLNK:
        printf("symlink\n");
        break;
    case S_IFREG:
        printf("regular file\n");
        break;
    case S_IFSOCK:
        printf("socket\n");
        break;
    default:
        printf("unknown?\n");
        break;
    }
    printf("文件: '%s'\n",argv[1]);
    printf("大小: %lld      ",(long long) sb.st_size);
    printf("块: %lld               ",(long long) sb.st_blocks);
    printf("IO块: %ld\n",(long) sb.st_blksize);
    printf("设备: %ld      ",sb.st_dev);//文件设备编号
    printf("Inode: %ld      ",sb.st_ino);//文件i节点标号
    printf("硬链接: %ld\n", (long) sb.st_nlink);
    printf("权限: %lo (octal)      ",(unsigned long) sb.st_mode);
    printf("Uid=%ld       Gid=%ld\n",(long) sb.st_uid, (long) sb.st_gid);
    printf("最近更改: %s", ctime(&sb.st_ctime));
    printf("最近访问: %s", ctime(&sb.st_atime));
    printf("最近改动: %s", ctime(&sb.st_mtime));
    printf("创建时间: -\n");
    exit(EXIT_SUCCESS);
}

测试代码

分别用mystat和stat查看文件mystat.c的信息

posted @ 2022-10-16 14:47  20201324徐源  阅读(45)  评论(0编辑  收藏  举报