#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <dirent.h>
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#define IS_APATH(p) (*(p) == '/')
#define IS_RPATH(p) (!(IS_APATH(p)))
void list_files(const char * dir_path);
int main(int argc, char * argv[])
{
char path[PATH_MAX] = {0};
if((argc == 2 && strcmp(argv[1], "--help") == 0)
|| argc != 2)
{
printf("Usage: %s <path>\n", argv[0]);
return EXIT_SUCCESS;
}
if(strlen(argv[1]) >= PATH_MAX)
{
fprintf(stderr, "Path length is too long!\n");
return EXIT_FAILURE;
}
if(IS_RPATH(argv[1]))
realpath(argv[1], path);
else
strncpy(path, argv[1], PATH_MAX);
list_files(path);
return EXIT_SUCCESS;
}
void list_files(const char * dir_path)
{
DIR * dirp;
struct dirent * dp;
bool is_root;
char path[PATH_MAX] = {0};
is_root = strcmp(dir_path, "/") == 0;
if((dirp = opendir(dir_path)) == NULL)
{
perror("opendir");
exit(EXIT_FAILURE);
}
while(true)
{
errno = 0;
if((dp = readdir(dirp)) == NULL)
break;
if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
continue;
snprintf(path, PATH_MAX, "%s/%s", (is_root ? "" : dir_path), dp->d_name);
if(dp->d_type == DT_DIR)
list_files(path);
else
printf("%s\n", path);
}
if(closedir(dirp) != 0)
{
perror("closedir");
exit(EXIT_FAILURE);
}
}
[代码实例][Linux系统编程]遍历目录
最新推荐文章于 2018-03-29 08:57:02 发布