一、目录的访问
功能说明:打开一个目录
原型:DIR* opendir(char *pathname);
返回值:
打开成功,返回一个目录指针
打开失败,则返回NULL
功能说明:访问指定目录中下一个连接的细节
原型:struct dirent* readdir(DIR *dirptr);
返回值:
返回一个指向dirent结构的指针,它包含指定目录中下一个连接的细节;
没有更多连接时,返回NULL
功能说明:关闭一个已经打开的目录
原型:int closedir (DIR *dirptr);
返回值:调用成功返回0,失败返回-1
二、目录信息结构体
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 */
};
三、目录的创建删除和权限设置
功能说明:用来创建一个称为pathname的新目录,它的权限位设置为mode
原型:int mkdir(char *pathname,mode_t mode);
返回值:调用成功返回0,失败返回-1
mkdir常犯错误是认为权限为0666和文件相同,通常来说目录是 需要可执行权限,不然我们不能够在下面创建目录。
功能说明:删除一个空目录
原型:int rmdir(char *pathname);
返回值:调用成功返回0,失败返回-1
功能说明:用来改变给定路径名pathname的文件的权限位
原型:
int chmod (char *pathname, mode_t mode);
int fchmod (int fd, mode_t mode);
返回值:调用成功返回0,失败返回-1
功能说明:用来改变文件所有者的识别号(owner id)或者它的用户组识别号(group ID)
原型:
int chown (char *pathname, uid_t owner,gid_t group);
int fchown (int fd, uid_t owner,gid_t group);
返回值:调用成功返回0,失败返回-1
示例程序:
/*************************************************************************
> File Name: file_ls.c
> Author: Simba
> Mail: dameng34@163.com
> Created Time: Sat 23 Feb 2013 02:34:02 PM CST
************************************************************************/
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<dirent.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(int argc, char *argv[])
{
DIR *dir = opendir(".");
struct dirent *de;
while ((de = readdir(dir)) != NULL)
{
if (strncmp(de->d_name, ".", 1) == 0)
continue; //忽略隐藏文件
printf("%s\n", de->d_name);
}
closedir(dir);
exit(EXIT_SUCCESS); // 等价于return 0
}
以上程序将当前目录的文件名进行输出,类似 ls 的功能,忽略隐藏文件。
参考:《APUE》
转载自http://blog.csdn.net/jnu_simba/article/details/8918396