Path: blob/main/test/dirent/test_readdir_unlink.c
4133 views
/*1* Copyright 2023 The Emscripten Authors. All rights reserved.2* Emscripten is available under two separate licenses, the MIT license and the3* University of Illinois/NCSA Open Source License. Both these licenses can be4* found in the LICENSE file.5*/67#include <dirent.h>8#include <errno.h>9#include <fcntl.h>10#include <stdio.h>11#include <string.h>12#include <sys/stat.h>13#include <unistd.h>1415int main() {16if (mkdir("test", 0777) != 0) {17printf("Unable to create dir 'test'\n");18return 1;19}2021for (int i = 0; i < 10; i++) {22char path[10];23snprintf(path, 10, "test/%d", i);24int fd = open(path, O_CREAT, 0777);25if (fd < 0) {26printf("Unable to create file '%s'\n", path);27return 1;28}29close(fd);30}3132DIR* dir = opendir("test");33if (!dir) {34printf("Unable to open dir 'test'\n");35return 1;36}3738struct dirent* dirent;3940while ((dirent = readdir(dir)) != NULL) {41if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) {42continue;43}44char path[10];45snprintf(path, 10, "test/%s", dirent->d_name);46if (unlink(path)) {47printf("Unable to unlink '%s'\n", path);48return 1;49}50printf("Unlinked '%s'\n", path);5152// Add a new file in the middle. This will not be visited (although it would53// be valid to visit it).54if (strcmp(dirent->d_name, "5") == 0) {55int fd = open("test/X", O_CREAT, 0777);56if (fd < 0) {57printf("Unable to create file 'test/X'\n");58return 1;59}60close(fd);61}62}6364closedir(dir);6566// The new file should still exist.67if (access("test/X", F_OK) != 0) {68printf("Expected file 'test/X' to exist\n");69return 1;70}71if (unlink("test/X")) {72printf("Unable to unlink 'test/X'\n");73return 1;74}7576if (rmdir("test")) {77printf("Unable to remove dir 'test'\n");78return 1;79}8081printf("success\n");8283return 0;84}858687