Skip to content

Instantly share code, notes, and snippets.

@przemoc
Last active February 6, 2018 14:52
Show Gist options
  • Save przemoc/2991908 to your computer and use it in GitHub Desktop.
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
/* 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;
}
@przemoc
Copy link
Author

przemoc commented Feb 6, 2018

commit d86957660f53549bf8157596a176048f47f8b38c
Author: Przemyslaw Pawelczyk <[email protected]>
Date:   2018-02-06 15:44:57 +0100

    xopen.c: Add copyright notice and MIT license notice.

commit f8c3bf03dd31de2a38c7ebf1d3e145ca09262126
Author: Przemyslaw Pawelczyk <[email protected]>
Date:   2018-02-06 15:48:34 +0100

    Add SPDX License Identifier to all source files.

    The Software Package Data Exchange (SPDX) is a good initiative, it has
    matured over time and deserves accelerated adoption in open-source.

    https://spdx.org/learn
    https://spdx.org/using-spdx
    https://spdx.org/license-list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment