Linux下遍历文件夹的实现
转自:http://blog.csdn.net/wallwind/article/details/7528474
linux C 遍历目录及其子目录
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
void listDir(char *path)
{
DIR *pDir ;
struct dirent *ent ;
int i=0 ;
char childpath[512];
pDir=opendir(path);
memset(childpath,0,sizeof(childpath));
while((ent=readdir(pDir))!=NULL)
{
if(ent->d_type & DT_DIR)
{
if(strcmp(ent->d_name,".")==0 ||strcmp(ent->d_name,"..")==0)
continue;
sprintf(childpath,"%s/%s",path,ent->d_name);
printf("path:%s/n",childpath);
listDir(childpath);
}
else
{
cout<<ent->d_name<<endl;
}
}
}
int main(int argc,char *argv[])
{
listDir(argv[1]);
return 0;
}
//
Linux C :遍历输出指定目录下的所有文件
在Linux下opendir()、readdir()和closedir()这三个函数主要用来遍历目录。在使用这三个函数前必须先包括以下两个头文件:
#include <sys/types.h>
#include <dirent.h>
opendir函数的原型为:
DIR *opendir(const char *name);
它返回一个DIR*类型,这就是一个句柄啦,你不用管它的内部结构是什么样的,只要知道这个句柄就是等一下要传给readdir()函数的参数就行了。
readdir函数的原型为:
struct dirent *readdir(DIR *dir);
看它的参数就知道该参数是opendir函数返回的句柄,而该函数的返回值是struct dirent* 类型,这里我们必须了解一下这个结构体:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
这个结构体的d_name存放的就是文件的名字,这里的文件包括普通文件,目录文件等等,在linux的思想中,所有的东西都是文件。
closedir函数的原型为:
int closedir(DIR *dir);
这个函数就不用多说了,一般有开(open),就有关(close),这样的结构经常可出看到,如fopen,fclose等等。
三个函数介绍完了,直接来一个例子吧:
**********************************************SearchDir.c****************************************************
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
char filename[256][256];
int len = 0;
int trave_dir(const char* path, int depth)
{
DIR *d; //声明一个句柄
struct dirent *file; //readdir函数的返回值就存放在这个结构体中
struct stat sb;
if(!(d = opendir(path)))
{
printf("error opendir %s!!!\n",path);
return -1;
}
while((file = readdir(d)) != NULL)
{
//把当前目录.,上一级目录..及隐藏文件都去掉,避免死循环遍历目录
if(strncmp(file->d_name, ".", 1) == 0)
continue;
strcpy(filename[len++], file->d_name); //保存遍历到的文件名
//判断该文件是否是目录,及是否已搜索了三层,这里我定义只搜索了三层目录,太深就不搜了,省得搜出太多文件
if(stat(file->d_name, &sb) >= 0 && S_ISDIR(sb.st_mode)&& depth <= 3)
{
trave_dir(file->d_name, depth + 1);
}
}
closedir(d);
return 0;
}
int main()
{
int depth = 1;
int i;
string str="/usr/keygoe/ini/";
trave_dir(str.c_str(),depth);
for(i = 0; i < len; i++)
{
printf("%s\t", filename[i]);
}
printf("\n");
return 0;
}
//
Linux下C语言遍历文件夹
学习了LINUX下用C语言遍历文件夹,一些心得
struct dirent中的几个成员:
d_type:4表示为目录,8表示为文件
d_reclen:16表示子目录或文件,24表示非子目录
经过本人亲自试验发现:d_reclen:16表示子目录或以.开头的隐藏文件,24表示普通文本文件,28为二进制文件,等等
d_name:目录或文件的名称
具体代码如下,仅供参考
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
void List(char *path)
{
struct dirent* ent = NULL;
DIR *pDir;
pDir=opendir(path);
while (NULL != (ent=readdir(pDir)))
{
if (ent->d_reclen==24)
{
if (ent->d_type==8)
{
printf("普通文件:%s\n", ent->d_name);
}
else
{
printf("子目录:%s\n",ent->d_name);
List(ent->d_name);
printf("返回%s\n",ent->d_name);
}
}
}
}
int main(int argc, char *argv[])
{
List(argv[1]);
return 0;
}
上面函数修改后:
void List(char *path)
{
printf("路径为[%s]\n", path);
struct dirent* ent = NULL;
DIR *pDir;
pDir=opendir(path);
//d_reclen:16表示子目录或以.开头的隐藏文件,24表示普通文本文件,28为二进制文件,还有其他……
while (NULL != (ent=readdir(pDir)))
{
printf("reclen=%d type=%d\t", ent->d_reclen, ent->d_type);
if (ent->d_reclen==24)
{
//d_type:4表示为目录,8表示为文件
if (ent->d_type==8)
{
printf("普通文件[%s]\n", ent->d_name);
}
}
else if(ent->d_reclen==16)
{
printf("[.]开头的子目录或隐藏文件[%s]\n",ent->d_name);
}
else
{
printf("其他文件[%s]\n", ent->d_name);
}
}
}
转CU,地址:
http://blog.chinaunix.net/u/29024/showart_484896.html
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void dir_scan(char *path, char *file);
int count = 0;
int main(int argc, char *argv[])
{
struct stat s;
if(argc != 2){
printf("one direction requried\n");
exit(1);
}
if(lstat(argv[1], &s) < 0){
printf("lstat error\n");
exit(2);
}
//判断一个路径是否是目录
if(!S_ISDIR(s.st_mode)){
printf("%s is not a direction name\n", argv[1]);
exit(3);
}
dir_scan("", argv[1]);
printf("total: %d files\n", count);
exit(0);
}
void dir_scan(char *path, char *file)
{
struct stat s;
DIR *dir;
struct dirent *dt;
char dirname[50];
memset(dirname, 0, 50*sizeof(char));
strcpy(dirname, path);
if(lstat(file, &s) < 0){
printf("lstat error\n");
}
if(S_ISDIR(s.st_mode)){
strcpy(dirname+strlen(dirname), file);
strcpy(dirname+strlen(dirname), "/");
if((dir = opendir(file)) == NULL){
printf("opendir %s/%s error\n");
exit(4);
}
if(chdir(file) < 0) {
printf("chdir error\n");
exit(5);
}
while((dt = readdir(dir)) != NULL){
if(dt->d_name[0] == '.'){
continue;
}
dir_scan(dirname, dt->d_name);
}
if(chdir("..") < 0){
printf("chdir error\n");
exit(6);
}
}else{
printf("%s%s\n", dirname, file);
count++;
}
}
linux c 下如何获得目录下的文件数目。
int main(int argc, char **argv)
{
DIR * pdir;
struct dirent * pdirent;
struct stat f_ftime;
int fcnt;/*文件数目统计*/
pdir=opendir("./");
if(pdir==NULL)
{ return(-1); }
fcnt=0;
for(pdirent=readdir(pdir);pdirent!=NULL;pdirent=readdir(pdir))
{
if(strcmp(pdirent->d_name,".")==0||strcmp(pdirent->d_name,"..")==0)continue;
if(stat(pdirent->d_name,&f_ftime)!=0) return -1 ;
if(S_ISDIR(f_ftime.st_mode)) continue; /*子目录跳过*/
fcnt++;
printf("文件:%s\n",pdirent->d_name);
}
printf("文件总数%d\n",fcnt);
closedir(pdir);
return 0;
}
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr, "cannot open directory: %s\n ", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry-> d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/**//* Found a directory, but ignore . and .. */
if(strcmp( ". ",entry-> d_name) == 0 ||
strcmp( ".. ",entry-> d_name) == 0)
continue;
printf( "%*s%s/\n ",depth, " ",entry-> d_name);
/**//* Recurse at a new indent level */
printdir(entry-> d_name,depth+4);
}
else printf( "%*s%s\n ",depth, " ",entry-> d_name);
}
chdir( ".. ");
closedir(dp);
}
/**//* Now we move onto the main function. */
int main(int argc, char* argv[])
{
char *topdir, pwd[2]= ". ";
if (argc != 2)
topdir=pwd;
else
topdir=argv[1];
printf( "Directory scan of %s\n ",topdir);
printdir(topdir,0);
printf( "done.\n ");
exit(0);
}
相关文章:

如何用Python画一棵漂亮的树
Tree海龟绘图turtle 在1966年,Seymour Papert和Wally Feurzig发明了一种专门给儿童学习编程的语言——LOGO语言,它的特色就是通过编程指挥一个小海龟(turtle)在屏幕上绘图。 海龟绘图(Turtle Graphics)后来…

windows7下,Java中利用JNI调用c++生成的动态库的使用步骤
1、从http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u2-download-1377129.html下载jdk-7u2-windows-i586.exe,安装到D:\ProgramFiles\Java,并将D:\ProgramFiles\Java\jdk1.7.0_02\bin添加到环境变量中; 2、从http://www.ec…

外观模式 - 设计模式学习
外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。 怎么叫更加容易使用呢?多个方法变成一个方法,在外观看来,只需知道这个功能完成…

Google最新论文:大规模深度推荐模型的特征嵌入问题有解了!
转载自深度传送门(ID: gh_5faae7b50fc5)导读:本文主要介绍下Google在大规模深度推荐模型上关于特征嵌入的最新论文。 一、背景大部分的深度学习模型主要包含如下的两大模块:输入模块以及表示学习模块。自从NAS[1]的出现以来&#…

[20181204]低版本toad 9.6直连与ora-12505.txt
[20181204]低版本toad 9.6直连与ora-12505.txt--//我们生产系统还保留有一台使用AMERICAN_AMERICA.US7ASCII字符集的数据库,这样由于toad新版本不支持该字符集的中文显示.--//我一直保留toad 9.6的版本,并且这个版本是32位的,我必须在我的机器另外安装10g 32位版本的客户端,这样…

Google揭露美国政府通过NSL索要用户资料
当美国联邦调查局FB或其他美国执法机构进行有关国家安全的调查时,能通过一种“国家安全密函National Security ,NSL)”向服务商索取其用户的个人资料,由于事关国家安全,因此该密函并不需经法院同意。但根据美国电子通讯隐私法的规…

Ubuntu下,Java中利用JNI调用codeblocks c++生成的动态库的使用步骤
1、 打开新立得包管理器,搜索JDK,选择openjdk-6-jdk安装; 2、 打开Ubuntu软件中心,搜索Eclipse,选择Eclipse集成开发环境,安装; 3、 打开Eclipse,File-->New-->Java Proj…

比Hadoop快至少10倍的物联网大数据平台,我把它开源了
作者 | 陶建辉转载自爱倒腾的程序员(ID: taosdata)导读:7月12日,涛思数据的TDengine物联网大数据平台宣布正式开源。涛思数据希望尽最大努力打造开发者社区,维护这个开源的商业模式,他们相信不将最核心的代…

Script:挖掘AWR实现查询SCN历史增长走势
AWR中记录了快照时间内calls to kcmgas的统计值,calls to kcmgas的意义在于通过递归调用获得一个新的SCN,该统计值可以看做SCN增长速度的主要依据,通过挖掘AWR可以了解SCN的增长走势,对于我们诊断SCN HEADROOM问题有所帮助&#x…

运动目标检测__光流法
以下内容摘自一篇硕士论文《视频序列中运动目标检测与跟踪算法的研究》: 1950年Gibson首先提出了光流的概念,光流(optical flow)法是空间运动物体在观测成像面上的像素运动的瞬时速度。物体在运动的时候,它在图像上对应点的亮度模式也在做相…

读完这45篇论文,“没人比我更懂AI了”
作者 | 黄海广 转载自机器学习爱好者(ID:ai-start-com) 导读:AI领域的发展会是IT中最快的。我们所看到的那些黑科技,其后无不堆积了大量论文,而且都是最新、最前沿的论文。从某种角度来讲,它们所用的技术跟…

深入理解JVM——虚拟机GC
对象是否存活 Java的GC基于可达性分析算法(Python用引用计数法),通过可达性分析来判定对象是否存活。这个算法的基本思想是通过一系列"GC Roots"的对象作为起始点,从这些节点开始向下搜索,搜索所走过的路径称为引用链,当…

2019年最新华为、BAT、美团、头条、滴滴面试题目及答案汇总
作者 | 苏克1900来源 | 高级农民工(ID:Mocun6)【导语】最近 GitHub 上一个库火了,总结了 阿里、腾讯、百度、美团、头条等国内主流大厂的技术面试题目,目前 Star 2000,还在持续更新中,预计会火下…

华胜天成ivcs云系统初体验2
重启完成以后,就看到传统的linux init3级别的登录界面。输入用户名root 密码:123456 (默认)接下来的工作是配置一些东西,让它跑起来。首先,要修改IP地址,还有机器名。输入命令:ivcs…

OpenCV中响应鼠标信息cvSetMouseCallback函数的使用
转自:http://blog.csdn.net/haihong84/article/details/6599838 程序代碼如下: #include <cv.h> #include <highgui.h> #include <stdio.h void onMouse(int event,int x,int y,int flags,void* param ); int main(int argc, char** …

日常遇到的一些问题或知识的笔记(一)
1、坑爹的sessionStorage 一直以为sessionStorage、localStorage跟cookie一样,只要存在,整个域名下都可见,直到新开了一个窗口tab页,惊奇的发现下面的sessionStorage丢失了! Web Storage 包含如下两种机制:…

你是“10倍工程师”吗?这个事,国外小伙伴们都快“吵”起来了
整理 | 夕颜出品 | AI科技大本营(ID:rgznai100)【导读】近日,推特上一个话题“10x工程师”异常火爆,引发的热议经久不散。这个话题由一位印度初创公司投资人 Shekhar Kirani 的一条推特引发,他写道;“如果…

运动目标跟踪__kalman
转自:http://blog.csdn.net/lindazhou2005/article/details/1534234 1、 什么是卡尔曼滤波器(What is the Kalman Filter?) 在学习卡尔曼滤波器之前,首先看看为什么叫“卡尔曼”。跟其他著名的理论(例如傅立叶变换&a…

Spring工厂常识
环境搭建导入Sring对应的jar包导入Spring依赖的commons-loggin包导入log4j.properties在src下导入ApplicationContext.xml在任意目录下是一个轻量级的企业开发框架核心:IOC , AOP编程IOC:也就是inverse of control 控制反转 就是讲创建对象的权利转移到工厂中,从而实现解耦合和…

iframe子页面操作父页面
2019独角兽企业重金招聘Python工程师标准>>> 最近经常用到iframe,用的最多的就是在子页面中操作父页面的方法或变量等,总结了用到的几种方法,如下: var tableName window.parent.frames["mainFrame"].tNam…

ASP.NET MVC动作过滤器
ASP.NET MVC中包含以下4种不同类型的Action Filter: 类型使用时机接口实现方法授权过滤器(Authorization Filter)在执行任何Filter或Action之前被执行,用于进行身份验证IAuthorizationFilterAuthorizeAttribute动作过滤器(Action Filter)在执行Action之前…

什么限制了GNN的能力?首篇探究GNN普适性与局限性的论文出炉!
作者 | Andreas Loukas译者 | 凯隐责编 | Jane出品 | AI科技大本营(ID: rgznai100)【导读】GNN是目前机器学习领域的热门网络之一,肯多研究与技术分享相比不可知的深度学习网络模型,GNN 有哪些吸引我们的优势及硬核实力。然而&…

OpenCV运动检测跟踪(blob track)框架组成模块详解
在..\opencv\doc\vidsurv文件夹中有三个doc文件,Blob_Tracking_Modules、Blob_Tracking_Tests、TestSeq,其中Blob_Tracking_Modules必须需要详读的。 “FG/BG Detection” module performsforeground/background segmentation for each pixel. “Blob E…

vi和软件安装
一 vi编辑器简介 vim 全屏幕纯文本编辑器 二 vim使用 1 vi 模式 vi 文件名 命令模式 输入模式 末行模式 命令----》输入 a:追加 i:插入 o:打开 i 命令----》末行 :w 保存 :q 不保存退出 2 命令模式操作 1)…

鸟哥学习笔记---网络安全基础
yum clean [packages|header|all] packages:将已下载的软件文件删除 headers:将下载的软件文件头删除 all:将所有容器数据都删除 添加镜像站点:mirrorlisthttp://ftp.twaren.net/Linux/CentOS/6/os/x86_64/ http://free.nchc.org.tw/drbl-core/i386/RPMS…

使用纯C++实现SQL Server2005 数据库读写操作详细步骤
环境:虚拟机windows xp,vs2008 SQLServer 2005 Express 数据库访问技术采用ADO。 需要安装的软件包括:microsoft_dotnetfxchs2.0.exe、WindowsInstaller-KB893803-v2-x86.exe、SQLEXPR32_CHS.EXE、SQLServer2005_SSMSEE.msi、SQLServer200…

硬核吃瓜!上万条数据撕开微博热搜真相
作者 | 徐麟来源 | 转载自数据森麟(ID:shujusenlin)吃瓜前言关于新浪微博,向来都是各路吃瓜群众聚集之地,大家在微博中可以尽情吃瓜,各种类型的瓜应有尽有,只有你想不到的,没有你吃不到的。微博…

python类的__slots__属性、__del__属性、上下文(__enter__和__exit__)、
常规情况下,类的属性字典是共享的,而实例的字典是独立的。如果一个类的属性较少,但是拥有很多的实例,这些实例的属性字典会占用较多的内存空间。对这样的类来说,为了节省内存空间,可以使用__slots__类变量代…

普通帧,关键帧,空白关键帧的区别
1. 特点 帧——是进行flash动画制作的最基本的单位,每一个精彩的flash动画都是由很多个精心雕琢的帧构成的,在时间轴上的每一帧都可以包含需要显示的所有内容,包括图形、声音、各种素材和其他多种对象。 关键帧——顾名思义,有关键…