#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <libgen.h>
#define PRINT_RED(format, ...) printf("\033[1;31m" format "\033[0m", ##__VA_ARGS__)
#define PRINT_GREEN(format, ...) printf("\033[1;32m" format "\033[0m", ##__VA_ARGS__)
#define PRINT_YELLOW(format, ...) printf("\033[1;33m" format "\033[0m", ##__VA_ARGS__)
#define PRINT_BULE(format, ...) printf("\033[1;34m" format "\033[0m", ##__VA_ARGS__)
#define PRINT_PURPLE(format, ...) printf("\033[1;35m" format "\033[0m", ##__VA_ARGS__)
#define PRINT_GREY(format, ...) printf("\033[1;37m" format "\033[0m", ##__VA_ARGS__)
void print_file(char *path)
{
struct stat st;
if (stat(path, &st) != 0) {
perror("stat fail");
exit(EXIT_FAILURE);
}
if (st.st_mode & S_IXUSR || st.st_mode & S_IXGRP || st.st_mode & S_IXOTH)
PRINT_GREEN("%s\n", basename(path));
else
PRINT_GREY("%s\n", basename(path));
}
void print_dir(char *root_dir, int level)
{
if (level == 1) {
struct stat st;
if (stat(root_dir, &st) != 0) {
perror("stat fail");
exit(EXIT_FAILURE);
}
if (st.st_mode & S_IFDIR) {
PRINT_BULE("%s\n", root_dir);
} else if (st.st_mode & S_IFREG) {
print_file(root_dir);
} else {
printf("%s无法识别\n", root_dir);
exit(EXIT_FAILURE);
}
}
DIR *dir = opendir(root_dir);
if (dir == NULL) {
return;
}
char path[1024];
struct dirent *de = NULL;
while ((de = readdir(dir)) != NULL) {
if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
continue;
if (de->d_type & DT_DIR) {
snprintf(path, sizeof(path), "%s/%s", root_dir, de->d_name);
for (int i = 0; i < level; i++)
printf(" ");
PRINT_YELLOW("|--");
PRINT_BULE("%s\n", de->d_name);
print_dir(path, level + 1);
} else if (de->d_type & DT_REG) {
for (int i = 0; i < level; i++)
printf(" ");
PRINT_YELLOW("|--");
snprintf(path, sizeof(path), "%s/%s", root_dir, de->d_name);
print_file(path);
} else {
//不处理其他类型的文件
}
}
closedir(dir);
}
//gcc -g -Wall -Wextra filetree.c -o filetree -std=gnu99
int main(int argc, char *argv[])
{
char root_dir[1024];
if (argc == 1) {
strcpy(root_dir, ".");
} else if (argc == 2) {
strcpy(root_dir, argv[1]);
} else {
printf("usage: %s [root_dir]\n", argv[0]);
exit(EXIT_FAILURE);
}
print_dir(root_dir, 1);
}