您的位置:首页 > 产品设计 > UI/UE

ls命令的简单实现

2017-10-28 11:04 423 查看
最近在看APUE,做下笔记。

ls命令的简单实现主要是dirent.h头文件里的结构体和函数的使用。

1. ls1.c代码如下:

#include "apue.h"
#include <dirent.h>

int
main(int argc, char *argv[])
{
DIR             *dp;
struct dirent   *dirp;

if (argc != 2)
err_quit("usage: ls directory_name");

if ((dp = opendir(argv[1])) == NULL)
err_sys("can't open %s", argv[1]);
while ((dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d_name);

closedir(dp);
exit(0);
}


2. dirent.h头文件介绍

dirent.h是类unix系统目录操作的头文件,包含了打开目录、读目录等等常用函数。

dirent.h位于/usr/include/ 和 /usr/include/bits/ 这2个目录下,

其中opendir 和readdir 2个函数在 /usr/include/dirent.h 中定义.

struct dirent 在 /usr/include/bits/dirent.h 中定义.

3.相关源码

我就不翻译了O(∩_∩)O~

3.1 struct dirent 的定义 (/usr/include/bits/dirent.h)

struct dirent
{
#ifndef __USE_FILE_OFFSET64
__ino_t d_ino;
__off_t d_off;
#else
__ino64_t d_ino;
__off64_t d_off;
#endif
unsigned short int d_reclen;
unsigned char d_type;
char d_name[256];       /* We must not include limits.h! */
};


/usr/include/bits/dirent.h 中提示永远不要是用这个目录下的dirent.h头文件替代/usr/include/dirent.h头文件。

3.2 DIR变量 (_dirstream结构体)

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


struct __dirstream
{
void *__fd;
char *__data;
int __entry_data;
char *__ptr;
int __entry_ptr;
size_t __allocation;
size_t __size;
__libc_lock_define (, __lock)
};


3.3 opendir函数

/* 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));


3.4 readdir函数

/* 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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 APUE