20191325mystat

# stat命令的实现-mysate

学习使用stat(1),并用C语言实现

**提交学习stat(1)的截图**

 

 

查看 testfile 文件的inode内容内容,可以用以下命令:

```
stat testfile
```

**inode 的内容**

inode 包含文件的元信息,具体来说有以下内容:

- 文件的字节数
- 文件拥有者的 User ID
- 文件的 Group ID
- 文件的读、写、执行权限
- 文件的时间戳,共有三个:ctime 指 inode 上一次变动的时间,mtime 指文件内容上一次变动的时间,atime 指文件上一次打开的时间。
- 链接数,即有多少文件名指向这个 inode
- 文件数据 block 的位置

stat结构体

```c
struct stat { dev_t st_dev; //文件的设备编号

ino_t st_ino; //节点

mode_t st_mode; //文件的类型和存取的权限

nlink_t st_nlink; //连到该文件的硬连接数目,刚建立的文件值为1

uid_t st_uid; //用户ID

gid_t st_gid; //组ID

dev_t st_rdev; //(设备类型)若此文件为设备文件,则为其设备编号

off_t st_size; //文件字节数(文件大小)

unsigned long st_blksize; //块大小(文件系统的I/O 缓冲区大小)

unsigned long st_blocks; //块数

time_t st_atime; //最后一次访问时间

time_t st_mtime; //最后一次修改时间

time_t st_ctime; //最后一次改变时间(指属性) };
```

**man -k ,grep -r的使用**

使用man -k stat | grep 2查询stat命令的系统调用,如图

man 2 stat查看stat()函数的使用方法

 

 

 

 

**伪代码**

首先判断输入中是否包含文件参数,如果有则继续,没有则提示用户输入错误。 然后声明结构体,并调用stat()函数给结构体赋值,将文件的设备编号、节点、文件的类型和存取的权限、连到该文件的硬链接数目等按顺序输出。

**产品代码 mystate.c,提交码云链接**

```c
#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 stat1;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (stat(argv[1], &stat1) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
printf("文件: %s\n",argv[1]);
printf("Inode: %ld\n", (long) stat1.st_ino);
printf("硬链接: %ld\n", (long) stat1.st_nlink);
printf("权限: Uid = %ld Gid = %ld\n",(long) stat1.st_uid, (long) stat1.st_gid);
printf("IO块: %ld ",(long) stat1.st_blksize);
switch (stat1.st_mode & S_IFMT)
{
case S_IFBLK: printf("块设备\n");
break;
case S_IFCHR: printf("character device\n");
break;
case S_IFDIR: printf("目录\n");
break;
case S_IFIFO: printf("FIFO/管道\n");
break;
case S_IFLNK: printf("符号链接\n");
break;
case S_IFREG: printf("普通文件\n");
break;
case S_IFSOCK: printf("socket\n");
break;
default: printf("未知?\n");
break;
}
printf("大小: %lld bytes\n",(long long) stat1.st_size);
printf("块: %lld\n",(long long) stat1.st_blocks);
printf("最近访问: %s", ctime(&stat1.st_atime));
printf("最近更改: %s", ctime(&stat1.st_mtime));
printf("最近改动: %s", ctime(&stat1.st_ctime));
exit(EXIT_SUCCESS);
}
```

**测试代码,mystat 与stat(1)对比,提交截图**

 

 

posted @ 2021-11-05 21:49  sy20191325  阅读(34)  评论(0编辑  收藏  举报