您的位置:首页 > 其它

递归列出指定目录下所有的符号链接文件

2014-06-14 17:49 274 查看
要求:打印输出指定目录下所有符号链接文件,若文件为子目录,则递归搜索子目录下的符号链接文件。

知识点:

int lstat(const char *restrict pathname, struct stat *restrict buf)

#include <sys/stat.h>

#include <unistd.h>

函数说明 lstat()与stat()作用完全相同,都是取得参数file_name所指的文件状态,其差别在于,当文件为符号连接时,lstat()会返回该link本身的状态。

符号链接(软链接)是一类特殊的文件, 其包含有一条以绝对路径或者相对路径的形式指向其它文件或者目录的引用。

代码:

#include<stdio.h>

#include<stdlib.h>

#include<sys/stat.h>

#include<unistd.h>

#include<errno.h>

#include<dirent.h>

#include<sys/types.h>

#define SIZE 1024

int dir_run(char *path)

{ DIR *dir;

dir = opendir(path);

if (dir == NULL)

{

return -1;

}

struct stat st;

struct dirent *entry;

char fullpath[SIZE];

while((entry = readdir(dir)) != NULL)

{

if((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))

{

continue;

}

sprintf(fullpath, "%s/%s", path, entry->d_name);

if(lstat(fullpath, &st) != 0)

{

continue;

}

if(S_ISLNK(st.st_mode))

{

printf("%s\n",entry->d_name);

}

if(S_ISDIR(st.st_mode))

{

dir_run(fullpath);

printf("\n");

}

}

closedir(dir);

return 0;

}

int main(int argc,char*argv[])

{

if(argc!=2)

{

printf("参数不正确!正确格式:./main filepath\n");

exit(1);

}

dir_run(argv[1]);

return 0 ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: