-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeek.c
91 lines (79 loc) · 3.34 KB
/
peek.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "headers.h"
int compareNames(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
void listFiles(const char *dirPath, int showHidden, int showDetails) {
DIR *dir = opendir(dirPath);
// printf("%s\n",dirPath);
if (dir == NULL) {
perror("opendir");
return;
}
// printf("123%s\n",dirPath);
struct dirent *entry;
char **fileNames = NULL;
int numFiles = 0;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.' && !showHidden) {
// printf("you are la\n");
continue;
}
if (numFiles == 0) {
// printf("you are la2\n");
fileNames = (char **)malloc(sizeof(char *));
} else {
fileNames = (char **)realloc(fileNames, (numFiles + 1) * sizeof(char *));
// printf("123%s\n",dirPath);
}
if (fileNames == NULL) {
perror("malloc/realloc");
return;
}
fileNames[numFiles] = strdup(entry->d_name);
numFiles++;
}
// printf("123%s\n",dirPath);
// printf("%s\n",fileNames[0]);
closedir(dir);
if (numFiles > 0) {
qsort(fileNames, numFiles, sizeof(char *), compareNames);
for (int i = 0; i < numFiles; i++) {
char filePath[512];
snprintf(filePath, sizeof(filePath), "%s/%s", dirPath, fileNames[i]);
struct stat fileStat;
if (stat(filePath, &fileStat) == 0) {
if (showDetails) {
char permissions[11];
strcpy(permissions, "----------");
if (S_ISDIR(fileStat.st_mode)) permissions[0] = 'd';
if (fileStat.st_mode & S_IRUSR) permissions[1] = 'r';
if (fileStat.st_mode & S_IWUSR) permissions[2] = 'w';
if (fileStat.st_mode & S_IXUSR) permissions[3] = 'x';
if (fileStat.st_mode & S_IRGRP) permissions[4] = 'r';
if (fileStat.st_mode & S_IWGRP) permissions[5] = 'w';
if (fileStat.st_mode & S_IXGRP) permissions[6] = 'x';
if (fileStat.st_mode & S_IROTH) permissions[7] = 'r';
if (fileStat.st_mode & S_IWOTH) permissions[8] = 'w';
if (fileStat.st_mode & S_IXOTH) permissions[9] = 'x';
struct passwd *pw = getpwuid(fileStat.st_uid);
struct group *gr = getgrgid(fileStat.st_gid);
struct tm *tm = localtime(&fileStat.st_mtime);
char timeStr[80];
strftime(timeStr, sizeof(timeStr), "%b %d %H:%M", tm);
printf("%s %ld %s %s %lld %s ", permissions, (long)fileStat.st_nlink,
pw->pw_name, gr->gr_name, (long long)fileStat.st_size, timeStr);
}
if (S_ISDIR(fileStat.st_mode)) {
printf(ANSI_COLOR_BLUE "%s" ANSI_COLOR_RESET "\n", fileNames[i]);
} else if (fileStat.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
printf(ANSI_COLOR_GREEN "%s" ANSI_COLOR_RESET "\n", fileNames[i]);
} else {
printf("%s\n", fileNames[i]);
}
}
free(fileNames[i]);
}
// printf("123%s\n",dirPath);
free(fileNames);
}
}