Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/test/dirent/test_readdir_unlink.c
4133 views
1
/*
2
* Copyright 2023 The Emscripten Authors. All rights reserved.
3
* Emscripten is available under two separate licenses, the MIT license and the
4
* University of Illinois/NCSA Open Source License. Both these licenses can be
5
* found in the LICENSE file.
6
*/
7
8
#include <dirent.h>
9
#include <errno.h>
10
#include <fcntl.h>
11
#include <stdio.h>
12
#include <string.h>
13
#include <sys/stat.h>
14
#include <unistd.h>
15
16
int main() {
17
if (mkdir("test", 0777) != 0) {
18
printf("Unable to create dir 'test'\n");
19
return 1;
20
}
21
22
for (int i = 0; i < 10; i++) {
23
char path[10];
24
snprintf(path, 10, "test/%d", i);
25
int fd = open(path, O_CREAT, 0777);
26
if (fd < 0) {
27
printf("Unable to create file '%s'\n", path);
28
return 1;
29
}
30
close(fd);
31
}
32
33
DIR* dir = opendir("test");
34
if (!dir) {
35
printf("Unable to open dir 'test'\n");
36
return 1;
37
}
38
39
struct dirent* dirent;
40
41
while ((dirent = readdir(dir)) != NULL) {
42
if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) {
43
continue;
44
}
45
char path[10];
46
snprintf(path, 10, "test/%s", dirent->d_name);
47
if (unlink(path)) {
48
printf("Unable to unlink '%s'\n", path);
49
return 1;
50
}
51
printf("Unlinked '%s'\n", path);
52
53
// Add a new file in the middle. This will not be visited (although it would
54
// be valid to visit it).
55
if (strcmp(dirent->d_name, "5") == 0) {
56
int fd = open("test/X", O_CREAT, 0777);
57
if (fd < 0) {
58
printf("Unable to create file 'test/X'\n");
59
return 1;
60
}
61
close(fd);
62
}
63
}
64
65
closedir(dir);
66
67
// The new file should still exist.
68
if (access("test/X", F_OK) != 0) {
69
printf("Expected file 'test/X' to exist\n");
70
return 1;
71
}
72
if (unlink("test/X")) {
73
printf("Unable to unlink 'test/X'\n");
74
return 1;
75
}
76
77
if (rmdir("test")) {
78
printf("Unable to remove dir 'test'\n");
79
return 1;
80
}
81
82
printf("success\n");
83
84
return 0;
85
}
86
87