请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

LINUX遍历文件夹【C语言版本】(原创)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

LINUX系统中,遍历文件夹的函数,C语言版本(在LINUX/Debian上编译、运行通过),可以遍历当前目录以及递归遍历子目录。

先把代码放在这里,方便以后查找!

/*
* ===========================================================================
*
* Filename: main.c
*
* Description: list the files
*
* Version: 1.0
* Created: 2010.12.28

* Compiler: gcc
* Author: puresky
*
* ============================================================================
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/dir.h>
#include <sys/stat.h>
#include <string.h>

//判断是否为目录

int IS_DIR(const char* path)
{
struct stat st;
lstat(path, &st);
return S_ISDIR(st.st_mode);
}

//遍历文件夹de递归函数
void List_Files_Core(const char *path, int recursive)
{
DIR *pdir;
struct dirent *pdirent;
char temp[256];
pdir = opendir(path);
if(pdir)
{
while(pdirent = readdir(pdir))
{
//跳过"."和".."
if(strcmp(pdirent->d_name, ".") == 0
|| strcmp(pdirent->d_name, "..") == 0)
continue;

sprintf(temp, "%s/%s", path, pdirent->d_name);

printf("%s\n", temp);
//当temp为目录并且recursive为1的时候递归处理子目录
if(IS_DIR(temp) && recursive)
{
List_Files_Core(temp, recursive);
}
}
}
else
{
printf("opendir error:%s\n", path);
}
closedir(pdir);

}
//遍历文件夹的驱动函数

void List_Files(const char *path, int recursive)
{
int len;
char temp[256];

//去掉末尾的'/'
len = strlen(path);
strcpy(temp, path);
if(temp[len - 1] == '/') temp[len -1] = '\0';

if(IS_DIR(temp))
{
//处理目录
List_Files_Core(temp, recursive);
}
else //输出文件
{
printf("%s\n", path);
}
}

int main(int argc, char** argv)
{
if(argc != 2)
{
printf("Usage: ./program absolutePath\n");
exit(0);
}

List_Files(argv[1], 1);
return 0;
}


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
字符串哈希(HASH)函数【来自GLIB】发布时间:2022-05-14
下一篇:
simhash算法的原理发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap