linux下c语言实现搜索根目录下所有文件
2017-11-09 17:01
381 查看
linux下c语言实现搜索根目录下所有文件(转-wangxiangshang)
头文件:#include<dirent.h> #include<sys/types.h> opendir(): 函数原型: DIR * opendir(const char* path); 打开一个目录,在失败的时候返回NULL(如果path对应的是文件,则返回NULL) DIR 结构体的原型为:struct_dirstream 在linux系统中: typedef struct __dirstream DIR; struct __dirstream { void *__fd; /* `struct hurd_fd' pointer for descriptor. */ char *__data; /* Directory block. */ int __entry_data; /* Entry number `__data' corresponds to. */ char *__ptr; /* Current pointer into the block. */ int __entry_ptr; /* Entry number `__ptr' corresponds to. */ size_t __allocation; /* Space allocated for the block. */ size_t __size; /* Total valid data in the block. */ __libc_lock_define (, __lock) /* Mutex lock for this structure. */ }; readdir(): 函数原型: struct dirent * readdir(DIR * dir_handle); 本函数读取dir_handle目录下的目录项,如果有未读取的目录项,返回目录项,否则返回NULL。 循环读取dir_handle,目录和文件都读 返回dirent结构体指针,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) 文件名,最长255字符 */ } closedir(): 函数原型: int closedir(DIR * dir_handle);
程序如下:
#include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> //搜索 指定目录下的所有文件及其子目录下的文件 void getFileName(char * dirPath) { DIR *dir=opendir(dirPath); if(dir==NULL) { printf("%s\n",strerror(errno)); return; } chdir(dirPath);//进入到当前读取目录 struct dirent *ent; while((ent=readdir(dir))!=NULL) { if(strcmp(ent->d_name,".")==0||strcmp(ent->d_name,"..")==0) { continue; } struct stat st; stat(ent->d_name,&st); if(S_ISDIR(st.st_mode)) { getFileName(ent->d_name); } else { printf("%s\n",ent->d_name); } } closedir(dir); chdir("..");//返回当前目录的上一级目录 } int main(int argc, char *argv[]) { getFileName("/home/gexin/program/"); return 0; }
相关文章推荐
- linux下c语言实现搜索根目录下所有文件(转-wangxiangshang)
- Linux下c语言实现将一个目录下的所有文件和目录复制到另一个目录下
- Linux下c语言实现将一个目录下的所有文件和目录复制到另一个目录下
- 利用Dataview实现搜索指定目录下的所有文件,以指定的条件排序(可以按文件名升降序,最后修改时间升降序)
- linux下c语言实现搜索根目录下所有文件
- UE4 C++实现搜索指定目录下的指定类型的所有文件
- 采用多线程和生产者消费者模式来实现对于一个目录以及所有子目录下的文件内容的搜索,打印出包含指定关键字的行.
- Linux下搜索所有文件,并删除文件,保留目录
- C#实现的列出目录下所有子目录和文件的程序(附思路)
- shell: 搜索某目录下所有文件中的某关键词
- C#实现的列出目录下所有子目录和文件的程序(附思路)
- 利用IO的知识,实现一个程序列出某个目录下的所有的”.java”文件。
- windows api 实现删除指定目录下的所有文件(包括子文件夹下的所有文件)
- find搜索目录下所有文件内容中的某个单词
- 习题13:编写程序,使用File类实现删除当前目录下的所有文件。
- Linux下c语言实现将一个目录下的所有文件和目录复制到另一个目录下
- 递归实现查找目录下的所有子目录和文件
- Java实现压缩一个目录下所有图片文件
- c++搜索目录下的所有文件
- 市面上所有号称"虚拟机","防火墙"的实时监控杀毒软件无一不是使用的IFSHOOK技术.但是同时也有一些朋友不断写MAIL给我打听如何实现读写的监控.下面给出用VTOOLSD写的代码.也就是所有实时杀毒软件的奥秘.同时,很多拦截文件操作的软件,例如对目录加