访问目录和文件属性

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
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值