1、ls产生一个文件名的列表,它大致是这样工作的:
open directory +-> read entry - end of dir? -+ |__ display file info | close directory <--------------+
2、目录是一种特殊的文件,它的内容是文件和目录的名字。与普通文件不同的是,目录文件永远不会空,每个目录至少包含2个特殊的项,即
“.”和“..”,其中
“.”不是当前目录,“..”表示上一级目录。
3、man 3 readdir
#include <sys/types.h> #include <dirent.h> DIR *opendir(const char *dir_name); struct dirent *readdir(DIR *dir_name); int readdir_r(DIR *dir_ptr, struct dirent *entry, struct dirent **result); long telldir(DIR *dir_ptr); void seekdir(DIR *dir_ptr, long location); void rewinddir(DIR *dir_ptr); int closedir(DIR *dir_ptr);
4、ls的算法:
main() opendir while (readdir) print d_name closedir
5、用stat得到文件信息:
man 2 stat
#include <sys/stat.h> int res = stat(const char *path, struct stat *buf); /* return 0 for success, -1 for error */
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 filesystem 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 */ };
6、man getpwuid
7、SUID 位告诉内核,运行这个程序的时候认为是由文件所有者在运行这个程序;SGID位告诉内核,运行这个程序的时候认为文件所属的组在运行这个程序;sticky位对于文件,在早期用于交换(swap)技术,对于目录而言被设计用来存放临时文件,如/tmp。
ls -l sample -rwsr-sr-t 1 root root 2345 Jul 24 00:45 sample
8、设置和修改文件的属性
#include <sys/types.h> #include <sys/stat.h> int res = chmod(const char *path, mod_t mode); int res = chmod(int fd, mode_t mode); /* On success, 0 is returned. On error, -1 is returned and errno is set appropriately */
#include <unistd.h> int chown(const char *path, uid_t owner, gid_t group); int fchown(int fd, uid_t owner, gid_t group); int lchown(const char *path, uid_t owner, gid_t group); /* On success, 0 is returned. On error, -1 is returned and errno is set appropriately */
9、修改最后修改时间和最后访问时间:
man utime
10、修改文件名
man 2 rename
目录与文件属性——《Unix/Linux编程实践教程》读书笔记
时间: 2024-10-15 04:46:59