stat命令的实现-mysate
任务详情
学习使用stat(1),并用C语言实现
1. 提交学习stat(1)的截图
2. man -k ,grep -r的使用
3. 伪代码
4. 产品代码 mystate.c,提交码云链接
5. 测试代码,mystat 与stat(1)对比,提交截图
学习使用stat命令
stat命令了解
stat指令:文件/文件系统的详细信息显示。
stat命令主要用于显示文件或文件系统的详细信息,该命令的语法格式如下:
stat命令-->用来显示文件的详细信息,包括inode, atime, mtime, ctime
适用场景:
查看文件或目录的诸如atime,mtime,ctime等信息即可使用stat命令,也可使用ls命令,但相比而言,stat还可以看到设备号,环境等信息。
stat(1)的截图
- 使用
man 1 stat
查看
-f 不显示文件本身的信息,显示文件所在文件系统的信息
-L 显示符号链接
-C 文件权限
-t 简洁模式,只显示摘要信息
man -k ,grep -r的使用
- 使用
man -k stat | grep 2
查找stat相关函数
- 使用
man 2 stat
学习函数
编写mystate.c伪代码
代码外操作:
- 用户运行 mystat.c 程序,输入文件名
- 由man 2 stat函数学习后可知调用stat函数实现功能
- 结构体struct stat:
代码需要完成的操作:
将文件的相关参数(从stat test.c
输出结果中引号前面的部分作为需要捕获的信息)。信息找到后,并定义printf语句将它们分别输出。
产品代码
mystat.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 sb;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>
", 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
");
break;
case S_IFCHR: printf("character device
");
break;
case S_IFDIR: printf("directory
");
break;
case S_IFIFO: printf("FIFO/pipe
");
break;
case S_IFLNK: printf("symlink
");
break;
case S_IFREG: printf("regular file
");
break;
case S_IFSOCK: printf("socket
");
break;
default: printf("unknown?
");
break;
}
printf("I-node number: %ld
", (long) sb.st_ino);
printf("Mode: %lo (octal)
",(unsigned long) sb.st_mode);
printf("Link count: %ld
", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld
",(long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes
",(long) sb.st_blksize);
printf("File size: %lld bytes
",(long long) sb.st_size);
printf("Blocks allocated: %lld
",(long long) sb.st_blocks);
printf("Last status change: %s", ctime(&sb.st_ctime));
printf("Last file access: %s", ctime(&sb.st_atime));
printf("Last file modification: %s", ctime(&sb.st_mtime));
exit(EXIT_SUCCESS);
}