您的位置:首页 > 运维架构 > Linux

Linux编程中目录内容的读取(实现ls功能)

2016-02-01 16:14 411 查看
dirent.h是POSIX.1标准定义的unix类目录操作的头文件,包含了许多UNIX系统服务的函数原型。

头文件的位置在/usr/include/dirent.h,里面有很多函数定义和宏,可以提供给我们非常丰富的目录处理方法。我们在编程中一般只需要简单的使用下面几个函数。

/* This is the data type of directory stream objects.
The actual structure is opaque to users.  */
typedef struct __dirstream DIR;

/* Open a directory stream on NAME.
Return a DIR stream on the directory, or NULL if it could not be opened.
This function is a possible cancellation point and therefore not marked with __THROW.  */
extern DIR *opendir (__const char *__name) __nonnull ((1));

/* Close the directory stream DIRP.
Return 0 if successful, -1 if not.
This function is a possible cancellation point and therefore not marked with __THROW.  */
extern int closedir (DIR *__dirp) __nonnull ((1));

/* Read a directory entry from DIRP.  Return a pointer to a `struct dirent' describing the entry,
or NULL for EOF or error.  The storage returned may be overwritten by a later readdir call on the same DIR stream.
If the Large File Support API is selected we have to use the appropriate interface.
This function is a possible cancellation point and therefore not marked with __THROW.  */
#ifndef __USE_FILE_OFFSET64
extern struct dirent *readdir (DIR *__dirp) __nonnull ((1));
#else


示例代码,实现ls功能(简单实现了-a参数):

#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#define FLAG_NOHIDE 0x01

int main(int argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
int opt;
unsigned char flag=0x00;

if (argc < 2)
{
printf("usage: ls directory_name\n");
exit(0);
}

while ((opt = getopt(argc, argv, "a")) != -1)
{
switch (opt)
{
case 'a':
flag |= FLAG_NOHIDE;
break;
}
}

// open the dir(the 2ed argv index is always argc-1 I guess)
if ((dp = opendir(argv[argc-1])) == NULL)
{
printf("error: can't open %s\n", argv[argc-1]);
exit(0);
}

// use readdir to get all the file struct
while ((dirp = readdir(dp)) != NULL)
{
if (!(flag & FLAG_NOHIDE))
{
if (dirp->d_name[0] == '.')
{
continue;
}
}
printf("%s\n", dirp->d_name);
}

closedir(dp);
return 0;
}


附上dirent的结构:

struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长256字符 */
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: