-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathls.c
132 lines (113 loc) · 2.28 KB
/
ls.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "colors.h"
typedef struct flags_{
bool dotFiles;
bool rawSize;
bool humanSize;
}flags;
typedef struct filesize_{
int size;
char unit;
}filesize;
//Prints and destroys a filesize struct, returns a null pointer
filesize* printFileSize(filesize* i){
printf("%d %c", i->size,i->unit);
free(i);
return 0x0;
}
void handleArgs(char* arg, flags* flag){
for(int i=1;i<strlen(arg);i++){
switch(arg[i]){
case 'a': flag->dotFiles = true;break;
case 'l': flag->rawSize = true;break;
case 'h': flag->humanSize = true;break;
default: printf("Unknown arg %c passed\n",arg[i]);break;
}
}
return;
}
//Initialize the flags struct, set all default values
flags* initFlags(){
flags* def = malloc(sizeof(flags));
if(def!=NULL){
def->dotFiles = false;
def->rawSize = false;
def->humanSize = false;
}
return def;
}
int getFileSize(struct dirent* file){
struct stat statbuf;
stat(file->d_name, &statbuf);
return statbuf.st_size;
}
void printFormattedSize(struct dirent* file, flags* flag){
if(!(flag->rawSize || flag->humanSize)){
return;
}
printf(KWHT);
printf(": ");
//Exceptions
switch(file->d_type){
case DT_DIR: printf("Directory");return;
}
filesize* size = malloc(sizeof(filesize));
size->unit = ' ';
size->size = getFileSize(file);
if(flag->humanSize){
char* units = " KMG";
int i = 0;
while(size->size > 1000){
size->size /= 1000;
i++;
}
size->unit = units[i];
}
printFileSize(size);
}
int main(int argc, char* argv[]){
flags* flags = initFlags();
char* abs = getcwd(NULL, 0);
//Flags
if(argc!=1){
for(int i=1;i<argc;i++){
if(argv[i][0]=='-'){
handleArgs(argv[i],flags);
}
}
}
DIR* stream = opendir(abs);
if(stream == NULL){
return -1;
}
struct dirent* cur;
while(true){
cur = readdir(stream);
if(cur==NULL){
break;
}
if(
(flags->dotFiles) ||
((cur->d_name)[0]!='.')){
switch(cur->d_type){
case DT_DIR: printf(KBLU);break;
case DT_REG: printf(KWHT);break;
}
printf(cur->d_name);
printFormattedSize(cur, flags);
printf("\n");
}
}
printf(KNRM);
closedir(stream);
free(abs);
free(flags);
return 0;
}