linux 怎么禁止遍历目录,linux下遍历目录功能实现

/*

编译:

dir:dir.c

gcc -o $@ $<

*/

#include   

#include   

#include   

#include   

#include    

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值