-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.c
95 lines (75 loc) · 1.62 KB
/
file.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
#include "file.h"
void addToStack(File **root, char *name, char isDir, char isExec, unsigned long size){
File *f=(File*)malloc(sizeof(File));
strncpy(f->name, name, NAMELEN);
f->size=size;
f->isDir=isDir;
f->isExec=isExec;
f->next=(*root);
*root=f;
}
File* listFiles(char *path){
DIR *dir=opendir(path);
if(dir==NULL) return NULL;
File *stack=NULL;
struct dirent *ent;
char fullPath[NAMELEN];
while((ent=readdir(dir))!=NULL){
if(ent->d_name[0]=='.') continue;
snprintf(fullPath, NAMELEN-1, "%s/%s", path, ent->d_name);
if(isDir(fullPath)) addToStack(&stack, ent->d_name, 1, 0, 0);
else addToStack(&stack, ent->d_name, 0,isExecutable(fullPath) , fileSize(fullPath));
}
closedir(dir);
return stack;
}
void freeFiles(File *files){
if(files==NULL) return;
do{
File *f=files->next;
free(files);
files=f;
}while(files!=NULL);
}
long fileSize(char *path){
struct stat st;
if(stat(path, &st)<0) return -1;
return st.st_size;
}
int isDir(char *path){
struct stat st;
if(stat(path, &st)<0) return -1;
return S_ISDIR(st.st_mode);
}
int isExecutable(char *path){
struct stat st;
if(stat(path, &st)<0) return -1;
return st.st_mode & S_IXUSR;
}
int dirExist(char *dir){
DIR* d=opendir(dir);
if(d){
closedir(d);
return 1;
}else{
return 0;
}
}
void sizeToH(unsigned long size, char *buff, size_t max_len){
char mj[3]={0, 'B', 0};
double s;
if(size>1000000000){
s=size/1000000000;
mj[0]='G';
}else if(size>1000000){
s=size/1000000;
mj[0]='M';
}else if(size>1000){
s=size/1000;
mj[0]='k';
}else{
s=size;
mj[0]=' ';
}
snprintf(buff, max_len, "%4.1f %s", s, mj);
}