-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdir_empty.cc
More file actions
72 lines (59 loc) · 1.45 KB
/
dir_empty.cc
File metadata and controls
72 lines (59 loc) · 1.45 KB
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
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <iostream>
#include <chrono>
#include <cstdlib>
using namespace std;
// A test program for C- & shell-based dir_empty implementations.
// To build:
// g++ -Wall -std=c++14 -o dir_empty dir_empty.cc
// Usage:
// ./dir_empty <dir>
int dir_empty_c(const char *path)
{
struct dirent *ent;
int ret = 1;
DIR *d = opendir(path);
if (!d) {
fprintf(stderr, "%s: ", path);
perror("");
return -1;
}
while ((ent = readdir(d))) {
if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, "..")))
continue;
ret = 0;
break;
}
closedir(d);
return ret;
}
int dir_empty_shell(const char *path)
{
char buf[512];
snprintf(buf, sizeof(buf), "test -n \"$(ls -A %s)\"", path);
int status = system(buf);
int exitcode = WEXITSTATUS(status);
return (exitcode == 1);
}
void test_dir_empty(int (*cb)(const char *path), const char *path)
{
auto start = chrono::steady_clock::now();
auto ret = cb(path);
if (ret >= 0)
printf("%s: %sempty\n", path, ret ? "" : "not ");
auto end = chrono::steady_clock::now();
std::cout << "Elapsed time "
<< chrono::duration_cast<chrono::microseconds>(end-start).count()
<< " us" << std::endl;
}
int main(int c, char **v)
{
if (c < 2) return -1;
for (int i = 1; i < c; i++) {
test_dir_empty(dir_empty_c, v[i]);
test_dir_empty(dir_empty_shell, v[i]);
}
return 0;
}