forked from NITDgpOS/manga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.c
134 lines (105 loc) · 2.4 KB
/
lib.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
132
133
134
#define PORTABLE
#ifndef PORTABLE
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
char* get_path(const char *file)
{
FILE *fp;
char cmd[5000];
char result[4096];
char *path;
int len;
sprintf(cmd, "readlink -f '%s'", file);
fp = popen(cmd, "r");
if (fp == NULL)
{
printf("Failed to run command %s\n", cmd);
exit(1);
}
fgets(result, 4095, fp);
len = strlen(result);
result[len - 1] = '\0';
path = (char *)malloc(len);
strcpy(path, result);
return path;
}
int get_file_names_in_dir(const char *dir, char ***list)
{
FILE *fp;
int files_in_dir, i = 0;
char result[4096];
char cmd[5000];
sprintf(cmd, "ls -l '%s' | sed '1d' | wc -l", dir);
fp = popen(cmd, "r");
if (fp == NULL)
{
printf("Failed to run command %s\n", cmd);
exit(1);
}
fgets(result, sizeof(result) - 1, fp);
files_in_dir = atol(result);
pclose(fp);
*list = (char **)malloc((files_in_dir + 1) * sizeof(char **));
#ifdef PORTABLE
int j = 0, ch;
sprintf(cmd,
"ls -l '%s' | sed -e '1d' | "
"awk '{$1=$2=$3=$4=$5=$6=$7=$8=\"\"; print $0}' | "
"sed -e 's/^ \\{1,\\}//'", dir);
fp = popen(cmd, "r");
if (fp == NULL)
{
printf("Failed to run command %s\n", cmd);
exit(1);
}
while (i < files_in_dir && !feof(fp))
{
ch = fgetc(fp);
if (ch < 32 || ch > 126)
{
if (j != 0)
{
result[j] = '\0';
(*list)[i] = (char *)malloc(j + 1);
strcpy((*list)[i], result);
j = 0;
++i;
}
continue;
}
result[j] = ch;
++j;
}
pclose(fp);
#else
DIR *mydir;
struct dirent *myfile;
mydir = opendir(dir);
while ((myfile = readdir(mydir)) != NULL)
{
if (myfile->d_name[0] != '.')
{
(*list)[i] = (char *)malloc(strlen(myfile->d_name) + 1);
strcpy((*list)[i], myfile->d_name);
++i;
}
}
closedir(mydir);
#endif
(*list)[i] = NULL;
return files_in_dir;
}
void free_file_list(char ***list)
{
int i = 0;
while ((*list)[i])
free((*list)[i++]);
free(*list);
}