-
Notifications
You must be signed in to change notification settings - Fork 0
/
ls.c
111 lines (94 loc) · 2.49 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
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <stdlib.h>
#define sz 100
int main(int argc, char **argv)
{
char *flag = argv[1], *args = argv[2];
struct stat file_stat;
struct dirent *entry;
DIR *dir;
if (strlen(args) == 0) //ls
dir = opendir(".");
else //ls path_name
dir = opendir(args);
if (dir == NULL){
dir = opendir(".");
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
if (strcmp(entry->d_name, args) == 0) {
printf("%s\n", args);
return 0;
}
}
printf("%s\n", "No such directory");
return 0;
}
if (strlen(flag) > 1) {
printf("\n%s\n", "Error: Invalid flag!");
return 0;
}
if (strlen(flag) == 0) {
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
printf("\n");
return 0;
}
else {
if (flag[0] == 'a') {
while ((entry = readdir(dir))) {
printf("%s\n", entry->d_name);
}
printf("\n");
}
else if (flag[0] == 'l') {
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
char * temp = (char*)malloc(200 * sizeof(char));
if (strlen(args) != 0)
strcpy(temp, args);
else
strcpy(temp, ".");
strcat(temp, "/");
strcat(temp, entry->d_name);
int check = stat(temp, &file_stat);
if (check == -1) {
perror("Error");
return 0;
}
printf((S_ISDIR(file_stat.st_mode)) ? "d" : "-");
printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");
printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");
printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");
printf(" ");
printf(" %d ", file_stat.st_uid);
printf(" %d ", file_stat.st_gid);
printf(" %ld ", file_stat.st_size);
char str[32];
strftime(str, sizeof(str), "%c", localtime(&file_stat.st_atime));
printf(" %s ", str);
printf("%s\n", entry->d_name);
}
}
else {
printf("%s", "Error: Invalid flag!");
}
return 0;
}
return 0;
}