linux命令之stat—mystat(必做)
linux命令之stat—mystat(必做)
1.首先man一下,查看stat函数没命令的帮助文档,并结合菜鸟教程(https://www.runoob.com/linux/linux-comm-stat.html)可得到stat命令,用于查看文件的 inode 的内容,即文件的属性信息
通过实际使用,得到以下截图:
可知以下命令对应操作
stat -f :显示文件系统的信息
stat -t :简化输出信息
stat * :显示该目录下所有文件及子目录的信息
2.使用man - -k stat |grep 2命令可以得到关于系统调用的stat命令
3.经过学习与个人理解,最终得到伪代码如下:
读取文件储存信息
依次打印所需获取信息
4.个人编写代码如下:
#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, "warnning! pls input: %s <pathname>\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("I-node number: %ld\n", (long) sb.st_ino);
printf("Mode: %lo (octal)\n",(unsigned long) sb.st_mode);
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n",(long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n",(long) sb.st_blksize);
printf("File size: %lld bytes\n",(long long) sb.st_size);
printf("Blocks allocated: %lld\n",(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);
}
5.
如图所示,经过对比可知,除顺序略有偏差以外,正常stat命令均已基本实现