Linux 文件与目录操作,ls 命令的实现

查看当前目录文件 ls directoryname/filename

ls 命令的功能

  1.列出目录的内容

  2.显示文件的信息

自己实现 ls 功能 需要掌握三点:

  1.如何列出目录的内容

  2.如何显示并读取文件的属性

  3.根据一个名字,如何能够判断它是目录还是文件

 

linux 在组织磁盘上的文件。

磁盘上的文件和目录被组成一颗目录树,每个节点都是目录或者文件。

每个文件都位于某个目录中。

ls 只需要考虑文件和目录两种情况,而无需考虑驱动器或分区。

目录:目录是一种特殊的文件,内容是文件和目录的名字。

每个目录的内容都会有 . 和 .. 这两个文件,分别指向当前和上一级目录

目录内容是包含一定数据结构的文本。

 

如何读取目录的内容: man -k direct | grep read

  readdir (2) - read directory entry
  readdir (3) - read a directory
  readdir_r (3) - read a directory

我们要找的应该是一个系统调用函数,所有 readdir (3) 是我们所需要的

man 3 readdir 

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);

struct dirent {
  ino_t d_ino; /* inode number */
  off_t d_off; /* offset to the next dirent */
  unsigned short d_reclen; /* length of this record */
  unsigned char d_type; /* type of file; not supported
  by all file system types */
  char d_name[256]; /* filename */
};

d_name 存放文件名

文件属性 struct stat

struct stat {
  dev_t st_dev; /* ID of device containing file */
  ino_t st_ino; /* inode number */
  mode_t st_mode; /* protection */
  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; /* blocksize for file system I/O */
  blkcnt_t st_blocks; /* number of 512B blocks allocated */
  time_t st_atime; /* time of last access */
  time_t st_mtime; /* time of last modification */
  time_t st_ctime; /* time of last status change */
};

posted @ 2021-12-19 23:32  愿得入睡  阅读(235)  评论(0)    收藏  举报