LINUX下目录遍历搜索文件程序,支持嵌套目录
来源:互联网 发布:抽奖软件 编辑:程序博客网 时间:2024/05/21 20:23
//LINUX下目录遍历搜索文件程序,支持嵌套目录
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
int do_search_dir(char *path);
int do_check_dir(char *fullpath, char* truefullpath);
void usage(char *apps);
int count = 0;
int
main(int argc,char **argv)
{
char fullpath[1024]={0};
if (argc != 2)
{
usage(argv[0]);
return -1;
}
if ( -1 ==do_check_dir(argv[1], fullpath) )
return -1;
do_search_dir(fullpath);
printf("/nThe total number of files is %d in the directory [%s]./n/n", count , fullpath);
return 0;
}
//return -1 search fail
//return 0 search ok
int
do_search_dir(char *path)
{
DIR *dir;
struct dirent *s_dir;
struct stat file_stat;
char currfile[1024]={0};
int len = strlen(path);
if (path[len-1] != '/')
{
path[len] = '/';
path[len+1] = 0;
}
printf("%s/n",path);
if ( (dir=opendir(path)) == NULL)
{
printf("opendir(path) error./n");
return -1;
}
while ((s_dir=readdir(dir))!=NULL)
{
if ((strcmp(s_dir->d_name,".")==0)||(strcmp(s_dir->d_name,"..")==0))
continue;
sprintf(currfile,"%s%s",path,s_dir->d_name);
stat(currfile,&file_stat);
if (S_ISDIR(file_stat.st_mode))
do_search_dir(currfile);
else
printf("%-32s/tOK/n",currfile);
count++;
//
//添加针对此文件的操作
//
}
closedir(dir);
return 0;
}
void
usage(char * apps)
{
printf("Directory to search for files./n/n");
printf("Usage: %s dirpath/n/n",apps);
}
//return -1 directory error
//args:
//input -->fullpath
//output -->truefullpath
int
do_check_dir(char *fullpath, char* truefullpath)
{
DIR *dir;
int pathlen, i ,k;
if ( (dir=opendir(fullpath)) == NULL)
{
printf("opendir fullpath error./nMaybe dir error./n");
return -1;
}
closedir(dir);
pathlen = strlen(fullpath);
if ( pathlen-1 != 0) // 路径长度不为1 的目录
{
if ( fullpath[pathlen-1] == '/' ) // 最后字节是'/'
{
for (i=pathlen-1; i>=0 ; i--)
{
if ( fullpath[i-1] != '/' && fullpath[i] == '/')
break;
}
fullpath[i+1] = 0;
}
else // 最后字节不是'/'
{
fullpath[pathlen] = '/';
fullpath[pathlen+1] = 0;
}
}
else // 路径长度为1 的目录
{
if (fullpath[pathlen-1] != '/')
{
fullpath[pathlen] = '/';
fullpath[pathlen+1] = 0;
}
else
fullpath[pathlen] = 0;
}
strcpy(truefullpath,fullpath);
return 0;
}
- LINUX下目录遍历搜索文件程序,支持嵌套目录
- LINUX下目录遍历搜索文件程序,支持嵌套目录
- 自己写的一个LINUX 下目录文件遍历程序
- Linux下遍历目录程序示例
- linux遍历目录下的文件
- LINUX下目录文件的遍历---编程
- Linux下遍历所有文件及目录
- linux 遍历目录下的文件
- 目录下搜索文件
- 取目录下所有文件支持linux
- linux下遍历目录
- linux下遍历目录
- linux下遍历目录
- Linux目录遍历实现 -- 列出当前目录下所有文件
- 遍历目录,获取目录下的文件
- Windows API遍历文件目录、搜索文件
- 遍历目录下所有文件
- 遍历目录下的文件
- dsaaaaaaa
- Havok Memory implementations
- 第一写博客
- winxp下文件夹拒绝访问的解决方法
- Hosts文件编辑器
- LINUX下目录遍历搜索文件程序,支持嵌套目录
- 千万数据的连续ID表,快速读取其中指定的某1000条数据?
- 关于recv函数只能接受一次数据
- 关于recv的一点困惑
- LINUX程序设计 -- 用getopt处理命令行参数
- u-boot遗留下来的bug解决!
- [SSL]身份认证与数字签名
- 计算中英文混合字符串的长度
- 求序列最大连续和