SDDSlib
Loading...
Searching...
No Matches
mkdir.c
Go to the documentation of this file.
1/**
2 * @file mkdir.c
3 * @brief Provides functionality to create directories recursively.
4 *
5 * @copyright
6 * - (c) 2002 The University of Chicago, as Operator of Argonne National Laboratory.
7 * - (c) 2002 The Regents of the University of California, as Operator of Los Alamos National Laboratory.
8 *
9 * @license
10 * This file is distributed under the terms of the Software License Agreement
11 * found in the file LICENSE included with this distribution.
12 *
13 * @author R. Soliday
14 */
15
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <sys/stat.h>
20#include <sys/types.h>
21#include <errno.h>
22
23#if defined(_WIN32)
24# include <windows.h>
25# include <direct.h>
26# include <io.h>
27# define mkdir(dirname, mode) _mkdir(dirname)
28# ifdef _MSC_VER
29# define strdup(str) _strdup(str)
30# endif
31#endif
32#if defined(vxWorks)
33# define mkdir(dirname, mode) mkdir(dirname)
34#endif
35
36/**
37 * @brief Creates a directory and all necessary parent directories.
38 *
39 * This function attempts to create the directory specified by `newdir`.
40 * It handles the creation of parent directories recursively. It aborts if an ENOENT
41 * error is encountered, but ignores other errors such as when the directory
42 * already exists.
43 *
44 * @param newdir The path of the directory to create.
45 * @return int Returns 1 if the directory was created successfully, 0 on error.
46 */
47int makedir(char *newdir) {
48 char *buffer = strdup(newdir);
49 char *p;
50 int len = strlen(buffer);
51
52 if (len <= 0) {
53 free(buffer);
54 return 0;
55 }
56 if (buffer[len - 1] == '/') {
57 buffer[len - 1] = '\0';
58 }
59 if (mkdir(buffer, 0755) == 0) {
60 free(buffer);
61 return 1;
62 }
63
64 p = buffer + 1;
65 while (1) {
66 char hold;
67
68 while (*p && *p != '\\' && *p != '/')
69 p++;
70 hold = *p;
71 *p = 0;
72 if ((mkdir(buffer, 0755) == -1) && (errno == ENOENT)) {
73 fprintf(stderr, "Couldn't create directory %s\n", buffer);
74 free(buffer);
75 return 0;
76 }
77 if (hold == 0)
78 break;
79 *p++ = hold;
80 }
81 free(buffer);
82 return 1;
83}
int makedir(char *newdir)
Creates a directory and all necessary parent directories.
Definition mkdir.c:47