文件系统
文件存储
首先了解如下文件存储相关概念:inode、dentry、数据存储、文件系统。
inode
其本质为结构体,存储文件的属性信息。如:权限、类型、大小、时间、用户、盘块位置.......也叫作文件属性管理结构,大多数的inode都存储在磁盘上。
少量常用、近期使用的inode会被缓存到内存中。
dentry
目录项
stat函数
获取文件属性,(从inode结构体中获取)
int stat(const char *path,struct stat *buf);
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; //最后一次改变时间(指属性)
};
参数:
path: 文件路径
buf:(传出参数) 存放文件属性
返回值:
成功:0
失败:-1 errno
#include#include #include #include #include #include int main(int argc,char *argv[]) { struct stat sbuf; int ret = stat(argv[1],&sbuf); if(ret == -1) { perror("stat error"); exit(1); } printf("file size:%ldn",sbuf.st_size); return 0; }
获取文件大小。
参数1:文件名
参数2:inode结构体指针(传出参数)
文件属性将通过传出参数返回给调用者
成功:返回0
失败:返回-1
#include#include #include #include #include int main(int argc,char *argv[]) { struct stat sb; int ret = stat(argv[1],&sb); if(ret == -1) { perror("stat error"); exit(1); } if(S_ISREG(sb.st_mode)) { printf("It's a regularn"); } else if(S_ISDIR(sb.st_mode)) { printf("It's a dirn"); } else if(S_ISFIFO(sb.st_mode)) { printf("It's a pipen"); } else if(S_ISLNK(sb.st_mode)) { printf("It's a sym linkn"); } return 0; }
lstat函数
int lstat(const char *path,struct stat *buf);
成功:返回0
失败:返回-1
设置errno为恰当值。
练习:给文件名,判断文件类型
穿透符合连接:stat:会;lstat:不会
#include#include #include #include #include int main(int argc,char *argv[]) { struct stat sb; int ret = lstat(argv[1],&sb); if(ret == -1) { perror("stat error"); exit(1); } if(S_ISREG(sb.st_mode)) { printf("It's a regularn"); } else if(S_ISDIR(sb.st_mode)) { printf("It's a dirn"); } else if(S_ISFIFO(sb.st_mode)) { printf("It's a pipen"); } else if(S_ISLNK(sb.st_mode)) { printf("It's a sym linkn"); } return 0; }
得出的结论:lstat会穿透符合连接



