300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > linux 怎么禁止遍历目录 linux下遍历目录功能实现

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

时间:2021-10-06 03:24:28

相关推荐

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;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。