首先感谢网上的分享者,是你们让我们站在巨人的肩膀上前行。
linux遍历文件,网上搜索一下,自己只是整理了一下,写点观后感,敲敲代码。
一、套路
1、DIR * opendir(路径):首先给出你想要的路径,路径为字符串,opendir回返回一个DIR *,这个在下一步中使用。
2、利用struct dirent * readdir(DIR *):将上一步得到的DIR放入到形参中,会得到一个struct dirent。
3、遍历…
其实思路不算难,三招剑法而已。接下来我们开始解析它。
二、这都是啥
1、opendir函数:
功能
打开一个目录,在失败的时候返回一个空的指针。
头文件:想在程序里用这个函数就必须包含它们
#include
DIR *pDir ;
char path[] = "~/Zy_program/c/test2/";//当前用户的Zy_program/c/test2/文件下
pDir = opendir(path);
2、readdir函数
头文件
#include
struct dirent *ent ;
DIR *pDir ;
//当前用户的Zy_program/c/test2/文件下
char path[] = "~/Zy_program/c/test2/";
pDir = opendir(path);
ent=readdir(pDir));
三、实战
这是别人写的,我试过了,稍加注释
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
void listDir(char *path)
{
DIR *pDir ;//首先通过opendir加工得到句柄
struct dirent *ent ;//readdir加工opendir句柄后,将文件信息存放此处
char childpath[512];//存放查询文件路径
pDir=opendir(path);//首先通过opendir将所给的路径加工一下存入DIR句柄中
memset(childpath,0,sizeof(childpath));//将查询路径先清理一下,防止干扰
while((ent=readdir(pDir))!=NULL)//调用readdir,不断得到文件信息
{
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
{
printf("%s\n",ent->d_name);
}
}
}
int main(int argc,char *argv[])
{
listDir(argv[1]);
return 0;
}