#include<sys/types.h>#include<dirent.h>
DIR *opendir(constchar*name);
功能:打开一个目录,获取目录流指针
参数:
name:目录名
返回值:
DIR是用来描述一个打开的目录文件的结构体类型,成功时返回目录流指针;出错时返回NULL。
readdir函数
#include<dirent.h>struct dirent *readdir(DIR *dirp);
功能:读取目录的信息
参数:
dirp:目录流指针
返回值:
成功:成功时返回目录流dirp中下一个目录项;
失败:NULL
如果目录的内容都读取完毕,则返回NULLstruct dirent是用来描述目录流中一个目录项的结构体类型
struct dirent {
ino_t d_ino;/* inode number */
off_t d_off;/* offset to the next dirent */unsignedshort d_reclen;/* length of this record */unsignedchar d_type;/* type of file; not supported
by all file system types */char d_name[256];/* filename */};
#include<sys/stat.h>intstat(constchar*path,struct stat *buf);intlstat(constchar*path,struct stat *buf);intfstat(int fd,struct stat *buf);
功能:stat/lstat/fstat函数用来获取文件属性
返回值:
成功时返回0;出错时返回EOF
如果path是符号链接stat获取的是目标文件的属性;而lstat获取的是链接文件的属性
文件信息的结构体
struct stat {//dev_t st_dev; /* ID of device containing file */ 文件所在设备的ID//ino_t st_ino; /* inode number */ inode节点号
mode_t st_mode;/* protection */ 模式(文件类型、访问权限)
nlink_t st_nlink;/* number of hard links */ 硬链接文件的连接数(硬连接)
uid_t st_uid;/* user ID of owner */ 用户id
gid_t st_gid;/* group ID of owner */ 组id
//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 */ 文件创建的时间
};S_ISREG(m) is it a regular file?S_ISDIR(m) directory?S_ISCHR(m) character device?S_ISBLK(m) block device?S_ISFIFO(m) FIFO (named pipe)?S_ISLNK(m) symbolic link?(Not in POSIX.1-1996.)S_ISSOCK(m) socket?(Not in POSIX.1-1996.)
The following flags are defined for the st_mode field:
S_IFMT 0170000 bit mask for the file type bit fields
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
S_ISUID 0004000 set-user-ID bit
S_ISGID 0002000 set-group-ID bit (see below)
S_ISVTX 0001000 sticky bit (see below)
S_IRWXU 00700 mask for file owner permissions
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
S_IRWXG 00070 mask for group permissions
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 mask for permissions for others (not in group)
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission