Linux编程中目录内容的读取(实现ls功能)
2016-02-01 16:14
411 查看
dirent.h是POSIX.1标准定义的unix类目录操作的头文件,包含了许多UNIX系统服务的函数原型。
头文件的位置在/usr/include/dirent.h,里面有很多函数定义和宏,可以提供给我们非常丰富的目录处理方法。我们在编程中一般只需要简单的使用下面几个函数。
示例代码,实现ls功能(简单实现了-a参数):
附上dirent的结构:
头文件的位置在/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字符 */ }
相关文章推荐
- centos彻底删除文件夹、文件命令
- Hello Makefile
- Linux的Graphics子系统分析
- Linux的LCD驱动分析
- Linux vmstat命令实战详解
- Linux的TTY驱动分析
- Linux的i2c驱动分析
- Linux的spi驱动分析
- Linux的USB驱动分析
- Linux的input子系统分析
- Linux的IRQ中断子系统分析
- Linux学习笔记之<让进程在后台可靠运行的几种方法>
- linux screen 命令详解
- 优化系统资源ulimit《高性能Linux服务器构建实战:运维监控、性能调优与集群应用》
- linux常用命令的英文单词缩写
- java开发需要掌握的linux命令
- LINUX的一些常用操作
- 优化Linux内核参数/etc/sysctl.conf sysctl 《高性能Linux服务器构建实战:运维监控、性能调优与集群应用》
- Linux内核OOM机制的详细分析(转)
- linux-vi命令