opendir
用来打开一个目录文件
DIR *opendir(const char *name);
DIR是用来描述一个打开的目录文件的结构体类型,成功返回目录流指针,出错时返回NULL。
readdir
用来读取目录流中的内容
struct dirent *readdir(DIR *dirp);
struct dirent 是用来描述目录流中一个目录的结构体
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* not an offset; see NOTES */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all filesystem types */
char d_name[256]; /* filename */
};
stat
用于获取文件属性;
int stat(const char *path,struct stat *buf);
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 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 */
};
示例代码
功能描述:将目录中的文件名称、大小、最后一次修改时间写到1.txt中;
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<time.h>
int main(){
FILE *p; //标准IO指针
struct stat st;
time_t t;
DIR *fp;
p = fopen("1.txt","w+"); //打开流
fp = opendir("."); //打开目录
struct dirent *dp;
while(dp = readdir(fp)){ //循环访问目录中的文件,知道全部访问返回NULL位置
stat(dp->d_name,&st);
t = st.st_mtime;
fprintf(p,"%s size:%d time:%s",dp->d_name,(int)st.st_size,ctime(&t));
}
}
执行结果
写入到1.txt的内容
ubuntu-14-s@ubuntu:~/1024/dir$ cat 1.txt
1.txt size:0 time:Fri Sep 24 20:20:10 2021
dir.c size:349 time:Fri Sep 24 20:19:57 2021
dir size:8841 time:Fri Sep 24 20:20:05 2021
.. size:4096 time:Thu Sep 23 23:20:15 2021
core size:253952 time:Thu Sep 23 23:25:31 2021
. size:4096 time:Fri Sep 24 20:20:05 2021