ls命令的简单实现
2017-10-28 11:04
423 查看
最近在看APUE,做下笔记。
ls命令的简单实现主要是dirent.h头文件里的结构体和函数的使用。
dirent.h位于/usr/include/ 和 /usr/include/bits/ 这2个目录下,
其中opendir 和readdir 2个函数在 /usr/include/dirent.h 中定义.
struct dirent 在 /usr/include/bits/dirent.h 中定义.
/usr/include/bits/dirent.h 中提示永远不要是用这个目录下的dirent.h头文件替代/usr/include/dirent.h头文件。
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));
相关文章推荐
- Linux系统编程_1_文件夹读取(实现简单ls命令)
- ls命令的简单实现
- Linux(Fedora)下ls命令的简单实现
- ls命令的简单实现源码
- linux ls命令的的简单实现APUE-1.4 文件和目录
- Linux 简单实现 ls -l 命令
- Linux系统编程_1_目录读取(实现简单ls命令)
- unix ls命令的一个简单实现
- 使用linux-c编程实现简单的ls命令
- unix ls命令的一个简单实现
- 实现一个简单的ls命令
- Linux下ls命令的简单模拟实现
- 实现一个简单的ls命令
- ls -l 命令的简单实现
- Linux&C编程之Linux系统命令“ls -l”的简单实现
- 列出文件名和属性——实现一个简单的ls命令
- ls命令的简单实现
- Linux下的 ls 命令的简单实现
- Linux命令简单实现 -- ls
- ls(1)命令的简单实现(一)