linux下c语言实现搜索根目录下所有文件(转-wangxiangshang)
2024-08-22 02:02:50
头文件:
#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+]; /* 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,".")==||strcmp(ent->d_name,"..")==)
{
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 ;
}
最新文章
- Struts中文件上传的一些规则...
- thinkphp __PUBLIC__的定义 __ROOT__等常量的定义
- bootstrapCDN和本地化
- php课程---练习(发布新闻)
- Leetcode 171 Excel Sheet Column Number 难度:0
- printf,sprintf,vsprintf 区别【转】
- 移动平台前端开发之WebApp代码技巧
- 使用u32过滤器设置基于mac地址的下载限制
- 怎样进行Android UI元素设计
- AngularJs指令(一)
- BZOJ2298: [HAOI2011]problem a
- Android的ListView分页功能
- FileInputStream 与 BufferedInputStream 效率对比
- 国内maven 仓库
- SQL学习之空值(Null)检索
- CentOS根分区占满
- 关于 Swift 4 中内存安全访问
- PCB差分线学习
- 通过Docker发布RestAPI遇到的种种问题
- 第52节:String,权限修饰符,方法,集合
热门文章
- java mysql 日期类型
- powershell中使用超大内存对象
- 在docker容器中安装和使用,linux版的powershell
- Djanog结合jquery实现ajax
- The property on could not be set to a &#39;Int16&#39; value.You must set this property to a non-null value of type ‘Int32’.”
- sqlite学习
- 快速了解IOC的几种姿势
- 在win7环境下安装python2.6.6
- BZOJ 3594 方伯伯的玉米田
- VS 2015 ,与Github的小问题笔记