Created
July 17, 2020 01:24
-
-
Save benaryorg/1e6fb711340b4e9c9afd08cbd33d7832 to your computer and use it in GitHub Desktop.
figuring out some things regarding directories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <err.h> | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
int main(void) | |
{ | |
const char *outer_path = "tmpdir"; | |
const char *inner_path = "inner"; | |
const char *file_path = "file"; | |
struct stat sb = {}; | |
int dirfd = 0; | |
int error = 0; | |
error = stat(outer_path, &sb); | |
if(error != 0 && errno == ENOENT) | |
{ | |
fprintf(stderr, "stat: ENOENT\n"); | |
if(mkdir(outer_path, 0750)) | |
{ | |
err(1, "mkdir"); | |
} | |
fprintf(stderr, "mkdir: ok\n"); | |
error = stat(outer_path, &sb); | |
} | |
if(error != 0) | |
{ | |
err(1, "stat"); | |
} | |
fprintf(stderr, "stat: ok\n"); | |
if(!(sb.st_mode&S_IFDIR)) | |
{ | |
errx(1, "dir is not a directory: %s", outer_path); | |
} | |
fprintf(stderr, "directory: ok\n"); | |
dirfd = open(outer_path, O_DIRECTORY); | |
if(dirfd < 0) | |
{ | |
err(1, "open"); | |
} | |
fprintf(stderr, "open: ok\n"); | |
/* | |
// if this is enabled the unlinkat call fails with "directory not empty" on this box | |
if((error = openat(dirfd, file_path, O_CREAT|O_APPEND)) < 0) | |
{ | |
err(1, "creat"); | |
} | |
close(error); | |
fprintf(stderr, "creat: ok\n"); | |
//*/ | |
if(unlinkat(AT_FDCWD, outer_path, AT_REMOVEDIR)) | |
{ | |
err(1, "unlink"); | |
} | |
fprintf(stderr, "unlink: ok\n"); | |
printf("waiting, press enter to continue\n"); | |
getchar(); | |
//* | |
// this fails with "no such file or directory" | |
// likely because the directory does have neither `.` nor `..` after the unlinkat, therefore ceasing to exist | |
if(mkdirat(dirfd, inner_path, 0)) | |
{ | |
err(1,"mkdirat"); | |
} | |
fprintf(stderr, "mkdirat: ok\n"); | |
//*/ | |
printf("waiting, press enter to continue\n"); | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment