Linux 目录流管理




“一切都是文件”,目录也是文件,即目录文件。

目录当然也是特殊的文件,里面存放的信息是子文件相关的信息。具体怎么存储可以不太关注。

ext3/4 文件系统下链式的存储结构。

在应用开发中,目录和文件一样,有目录流的概念。

fopen opendir

fread/…. readdir

ftell telldir

fseek seekdir

rewind rewinddir

fwrite mkdir/rmdir

fclose closedir

当前的工作路径的问题。

DIR *opendir(const char *name); //打开给定路径下的目录,返回目录流

DIR *fdopendir(int fd);

int closedir(DIR *dirp);

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

int readdir_r(DIR *dirp, struct dirent *entry, structdirent **result);

这个函数每执行一次,返回一个目录条目(就是一个子文件或者子目录的信息),当结束后,返回

NULL,并且向下指向下一个目录条件。

struct dirent:

On Linux, the dirent structure is defined as follows:

struct dirent {

ino_t d_ino; /* inode number */ //在当前文件系统下,这个文件的惟一编号

off_t d_off; /* offset to the next dirent */

unsigned short d_reclen; /* length of this record */

unsigned char d_type; /* type of file; not supported //类型,并不是所有的系统支持

by all file system types */

char d_name[256]; /* filename */ //子文件或者子目录名

};

文件类型:普通文件,目录文件,链接文件,字符设备文件,块设备文件,socket,管道文件。

#define S_IFSOCK 0140000

#define S_IFLNK 0120000

#define S_IFREG 0100000

#define S_IFBLK 0060000

#define S_IFDIR 0040000

#define S_IFCHR 0020000

#define S_IFIFO 0010000

以.开头的文件在Linux 系统下是我们隐藏文件。另外,readdir 并没有对读出的文件列表进行排序。

如果要排序呢?

int scandir(const char *dirp, //操作的目录

struct dirent ***namelist, //存放匹配的子文件及目录信息位置,空间自动的调用malloc

int (*filter)(const struct dirent *), //过滤掉哪些目录条目函数

int (*compar)(const struct dirent **, const struct dirent**)); //排序函数

int alphasort(const void *a, const void *b);

int versionsort(const void *a, const void *b);

The scandir() function scans the directory dirp, callingfilter() on each directory entry. Entries for

which filter() returns nonzero are stored in stringsallocated via malloc(3), sorted using qsort(3) with

the comparison function compar(), and collected in arraynamelist which is allocated via malloc(3). If

filter is NULL, all entries are selected.

读取dirp 所指向的目录,返回的子文件及子目录信息首先经过filter 函数过滤,并经过compar 方式

进行排序,然后分配空间存储,最后将该地址存储namelist 下。

完成后,需要释放空间。

int mkdir(const char *pathname, mode_t mode);

跟创建文件类似。

int rmdir(const char *pathname);

每执行一个程序,其实有一个当前工作路径。默认情况下,这个工作路径为执行文件的当前目录。

可以用

char *getcwd(char *buf, size_t size);

char *getwd(char *buf);

char *get_current_dir_name(void);

如果要修改当前工作路径,使用 chdir。

int chdir(const char *path);

int fchdir(int fd);

怎么来实现一个目录的递归操作:

(1)用递归来实现。

(2)用队列来实现。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值