hjl / source-git / glibc

Forked from source-git/glibc 3 years ago
Clone

Blame support/xmkdirp.c

Packit b0207b
/* Error-checking replacement for "mkdir -p".
Packit b0207b
   Copyright (C) 2018 Free Software Foundation, Inc.
Packit b0207b
   This file is part of the GNU C Library.
Packit b0207b
Packit b0207b
   The GNU C Library is free software; you can redistribute it and/or
Packit b0207b
   modify it under the terms of the GNU Lesser General Public
Packit b0207b
   License as published by the Free Software Foundation; either
Packit b0207b
   version 2.1 of the License, or (at your option) any later version.
Packit b0207b
Packit b0207b
   The GNU C Library is distributed in the hope that it will be useful,
Packit b0207b
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit b0207b
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit b0207b
   Lesser General Public License for more details.
Packit b0207b
Packit b0207b
   You should have received a copy of the GNU Lesser General Public
Packit b0207b
   License along with the GNU C Library; if not, see
Packit b0207b
   <http://www.gnu.org/licenses/>.  */
Packit b0207b
Packit b0207b
#include <support/support.h>
Packit b0207b
#include <support/check.h>
Packit b0207b
#include <support/xunistd.h>
Packit b0207b
Packit b0207b
#include <stdlib.h>
Packit b0207b
#include <string.h>
Packit b0207b
#include <errno.h>
Packit b0207b
Packit b0207b
/* Equivalent of "mkdir -p".  Any failures cause FAIL_EXIT1 so no
Packit b0207b
   return code is needed.  */
Packit b0207b
Packit b0207b
void
Packit b0207b
xmkdirp (const char *path, mode_t mode)
Packit b0207b
{
Packit b0207b
  struct stat s;
Packit b0207b
  const char *slash_p;
Packit b0207b
  int rv;
Packit b0207b
Packit b0207b
  if (path[0] == 0)
Packit b0207b
    return;
Packit b0207b
Packit b0207b
  if (stat (path, &s) == 0)
Packit b0207b
    {
Packit b0207b
      if (S_ISDIR (s.st_mode))
Packit b0207b
	return;
Packit b0207b
      errno = EEXIST;
Packit b0207b
      FAIL_EXIT1 ("mkdir_p (\"%s\", 0%o): %m", path, mode);
Packit b0207b
    }
Packit b0207b
Packit b0207b
  slash_p = strrchr (path, '/');
Packit b0207b
  if (slash_p != NULL)
Packit b0207b
    {
Packit b0207b
      while (slash_p > path && slash_p[-1] == '/')
Packit b0207b
	--slash_p;
Packit b0207b
      if (slash_p > path)
Packit b0207b
	{
Packit b0207b
	  char *parent = xstrndup (path, slash_p - path);
Packit b0207b
	  xmkdirp (parent, mode);
Packit b0207b
	  free (parent);
Packit b0207b
	}
Packit b0207b
    }
Packit b0207b
Packit b0207b
  rv = mkdir (path, mode);
Packit b0207b
  if (rv != 0)
Packit b0207b
    FAIL_EXIT1 ("mkdir_p (\"%s\", 0%o): %m", path, mode);
Packit b0207b
Packit b0207b
  return;
Packit b0207b
}