Last active
February 6, 2018 14:52
-
-
Save przemoc/2991908 to your computer and use it in GitHub Desktop.
How to open a file and create all needed directories along the way - http://stackoverflow.com/q/11147850/241521
This file contains hidden or 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
| /* SPDX-License-Identifier: MIT */ | |
| /* | |
| * Copyright (C) 2012 Przemyslaw Pawelczyk <[email protected]> | |
| * | |
| * This code is licensed under the terms of the MIT license. | |
| * https://opensource.org/licenses/MIT | |
| */ | |
| #include <errno.h> | |
| #include <fcntl.h> | |
| #include <string.h> | |
| #include <sys/stat.h> | |
| #include <unistd.h> | |
| /* Look out! It modifies pathname! */ | |
| int xopen(char *pathname, int flags, mode_t mode, mode_t dirmode) | |
| { | |
| int fd, errsv; | |
| int dirfd = AT_FDCWD; | |
| char *ptr = pathname; | |
| while (*ptr == '/') | |
| ptr++; | |
| for (;;) { | |
| strsep(&ptr, "/"); | |
| if (ptr == NULL) { | |
| fd = openat(dirfd, pathname, flags, mode); | |
| break; | |
| } | |
| while (*ptr == '/') | |
| ptr++; | |
| if (*ptr == '\0') { | |
| errno = EISDIR; | |
| fd = -1; | |
| break; | |
| } | |
| if ((fd = mkdirat(dirfd, pathname, dirmode)) < 0 && errno != EEXIST) | |
| break; | |
| if ((fd = openat(dirfd, pathname, O_DIRECTORY)) < 0) | |
| break; | |
| if (dirfd != AT_FDCWD) | |
| close(dirfd); | |
| dirfd = fd; | |
| pathname = ptr; | |
| } | |
| errsv = errno; | |
| if (dirfd != AT_FDCWD) | |
| close(dirfd); | |
| errno = errsv; | |
| return fd; | |
| } |
Author
przemoc
commented
Feb 6, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment