目录
一、打开目录 --- opendir
函数原型
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
参数 :
name : 要打开的目录名
返回值 :
成功返回目录流指针,失败返回NULL
示例:打开当前目录
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main()
{
DIR *dir = opendir(".");//打开当前目录
if(dir == NULL)//打开失败
{
perror("opendir");
return -1;
}
printf("opendir success!\n");
return 0;
}
二、读取目录 ---readdir
一次只能随机读取一个目录项;
函数原型
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct dirent {
char d_name[256]; /* 文件名 */
};
参数 :
name : 要关闭的目录名
返回值 :
成功返回目录流指针,失败返回NULL
示例:查看当前目录下的文件
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main()
{
DIR *dir = opendir(".");
if(NULL == dir)
{
perror("opendir");
return -1;
}
struct dirent *buf = NULL;
while((buf = readdir(dir)) != NULL)//判断循环是否结束
{
if(buf->d_name[0] != '.')//判断隐藏文件
{
printf("%s ", buf->d_name);
}
}
printf("\n");
return 0;
}
三、关闭目录 --- closedir
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
参数 :
dirp : 目录流指针
返回值 :
成功返回0,失败返回NULL
四、获取文件属性 --- lstat
函数原型
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct *statbuf);
int fstat(int fd, struct stat *Statbuf);//通过文件描述符获取文件信息
int lstat(const char *pathname, struct *statbuf);//通过文件名获取文件信息
参数 :
pathname : 文件名
statbuf : 存放文件信息的结构体地址
返回值 :
成功返回0,失败返回-1
4.1 文件属性结构体
struct stat
{
mode_t st_mode; //文件类型
nlink_t st_nlink; //文件硬连接数
uid_t st_uid; //用户ID
gid_t st_gid; //用户组ID
off_t st_size; //文件大小
struct timespec st_mtim; //最后修改文件的时间
#define st_mtim,tv_sec
}getgrgid--得到用户组名的函数:
头文件:#include <grp.h>
getpwuid--得到用户名的函数:
头文件:#include <pwd.h>
4.2 获取文件类型
获取文件类型:
S_IFMT 0170000 bit mask for the file type bit filed --- 文件类型掩码
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 --- 管道文件
判断:如果 st_mode & S_TFMT 等于对应文件类型宏,则文件类型宏对应类型就为文件类型
4.3 获取文件权限
用户权限
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
用户组权限S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
其他用户权限
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
判断方法:st_mode & 对应权限宏 == 宏本身 表示具有该权限