Make directory path: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|REXX}}: elided some blank lines.)
m (→‎{{header|Wren}}: Changed to Wren S/H (future CLI version))
 
(47 intermediate revisions by 32 users not shown)
Line 1: Line 1:
{{task|File System Operations}}
{{task|File System Operations}}

;Task:
Create a directory and any missing parents.
Create a directory and any missing parents.


Line 9: Line 11:


It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
<br><br>

=={{header|11l}}==
<syntaxhighlight lang="11l">fs:create_dirs(path)</syntaxhighlight>

=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Command_Line;
with Ada.Directories;
with Ada.Text_IO;

procedure Make_Directory_Path is
begin
if Ada.Command_Line.Argument_Count /= 1 then
Ada.Text_IO.Put_Line ("Usage: make_directory_path <path/to/dir>");
return;
end if;

declare
Path : String renames Ada.Command_Line.Argument (1);
begin
Ada.Directories.Create_Path (Path);
end;
end Make_Directory_Path;</syntaxhighlight>

=={{header|Aime}}==
<syntaxhighlight lang="aime">void
mkdirp(text path)
{
list l;
text p, s;

file().b_affix(path).news(l, 0, 0, "/");

for (, s in l) {
p = p + s + "/";
trap_q(mkdir, p, 00755);
}
}

integer
main(void)
{
mkdirp("./path/to/dir");

0;
}</syntaxhighlight>

=={{header|AppleScript}}==
AppleScript is not a cross-platform language so this is a macOS-only solution.
In post-Yosemite AppleScript we can draw on the macOS Foundation classes,
which include the NSFileManager method:
`createDirectoryAtPath:withIntermediateDirectories:attributes:error:`

<syntaxhighlight lang="applescript">use framework "Foundation"
use scripting additions


-- createOrFindDirectoryMay :: Bool -> FilePath -> Maybe IO ()
on createOrFindDirectoryMay(fp)
createDirectoryIfMissingMay(true, fp)
end createOrFindDirectoryMay


-- createDirectoryIfMissingMay :: Bool -> FilePath -> Maybe IO ()
on createDirectoryIfMissingMay(blnParents, fp)
if doesPathExist(fp) then
nothing("Directory already exists: " & fp)
else
set e to reference
set ca to current application
set oPath to (ca's NSString's stringWithString:(fp))'s ¬
stringByStandardizingPath
set {bool, nse} to ca's NSFileManager's ¬
defaultManager's createDirectoryAtPath:(oPath) ¬
withIntermediateDirectories:(blnParents) ¬
attributes:(missing value) |error|:(e)
if bool then
just(fp)
else
nothing((localizedDescription of nse) as string)
end if
end if
end createDirectoryIfMissingMay

-- TEST ----------------------------------------------------------------------
on run
createOrFindDirectoryMay("~/Desktop/Notes/today")
end run

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- doesPathExist :: FilePath -> IO Bool
on doesPathExist(strPath)
set ca to current application
ca's NSFileManager's defaultManager's ¬
fileExistsAtPath:((ca's NSString's ¬
stringWithString:strPath)'s ¬
stringByStandardizingPath)
end doesPathExist

-- just :: a -> Just a
on just(x)
{nothing:false, just:x}
end just

-- nothing :: () -> Nothing
on nothing(msg)
{nothing:true, msg:msg}
end nothing</syntaxhighlight>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">write.directory "path/to/some/directory" ø</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
BEGIN {
BEGIN {
Line 26: Line 143:
return system(cmd)
return system(cmd)
}
}
</syntaxhighlight>
</lang>
<p>sample command and output under Windows 8:</p>
<p>sample command and output under Windows 8:</p>
<pre>
<pre>
Line 35: Line 152:
'\TEMP\A\B C' created
'\TEMP\A\B C' created
</pre>
</pre>

=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <libgen.h>
#include <libgen.h>
Line 67: Line 185:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>

=={{header|Common Lisp}}==
=={{header|C sharp|C#}}==
<lang lisp>
<syntaxhighlight lang="csharp">System.IO.Directory.CreateDirectory(path)</syntaxhighlight>
(ensure-directories-exist "your/path/name")

</lang>
=={{header|C++|CPP}}==
<syntaxhighlight lang="cpp">
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
if(argc != 2)
{
std::cout << "usage: mkdir <path>\n";
return -1;
}

fs::path pathToCreate(argv[1]);

if (fs::exists(pathToCreate))
return 0;

if (fs::create_directories(pathToCreate))
return 0;
else
{
std::cout << "couldn't create directory: " << pathToCreate.string() << std::endl;
return -1;
}
}
</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn mkdirp [path]
<syntaxhighlight lang="clojure">(defn mkdirp [path]
(let [dir (java.io.File. path)]
(let [dir (java.io.File. path)]
(if (.exists dir)
(if (.exists dir)
true
true
(.mkdirs dir))))</lang>
(.mkdirs dir))))</syntaxhighlight>

=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(ensure-directories-exist "your/path/name")
</syntaxhighlight>

=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio;

void main() {
makeDir("parent/test");
}

/// Manual implementation of what mkdirRecurse in std.file does.
void makeDir(string path) out {
import std.exception : enforce;
import std.file : exists;
enforce(path.exists, "Failed to create the requested directory.");
} body {
import std.array : array;
import std.file;
import std.path : pathSplitter, chainPath;

auto workdir = "";
foreach (dir; path.pathSplitter) {
workdir = chainPath(workdir, dir).array;
if (workdir.exists) {
if (!workdir.isDir) {
import std.conv : text;
throw new FileException(text("The file ", workdir, " in the path ", path, " is not a directory."));
}
} else {
workdir.mkdir();
}
}
}</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IOUtils}}
<syntaxhighlight lang="delphi">
program Make_directory_path;

{$APPTYPE CONSOLE}

uses
System.SysUtils,
System.IOUtils;

const
Path1 = '.\folder1\folder2\folder3'; // windows relative path (others OS formats are acepted)
Path2 = 'folder4\folder5\folder6';

begin
// "ForceDirectories" work with relative path if start with "./"
if ForceDirectories(Path1) then
Writeln('Created "', path1, '" sucessfull.');

// "TDirectory.CreateDirectory" work with any path format
// but don't return sucess, requere "TDirectory.Exists" to check
TDirectory.CreateDirectory(Path2);
if TDirectory.Exists(Path2) then
Writeln('Created "', path2, '" sucessfull.');
Readln;
end.</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
Tries to create the directory `path`. Missing parent directories are created.
Tries to create the directory `path`. Missing parent directories are created.
<lang elixir>File.mkdir_p("./path/to/dir")</lang>
<syntaxhighlight lang="elixir">File.mkdir_p("./path/to/dir")</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
ERRE has the procedure "OS_MKDIR" in PC.LIB standard library, that creates a directory with
ERRE has the procedure "OS_MKDIR" in PC.LIB standard library, that creates a directory with
all missing parents. Existing directory are simply ignored.
all missing parents. Existing directory are simply ignored.
<lang ERRE>OS_MKDIR("C:\EXAMPLES\03192015")</lang>
<syntaxhighlight lang="erre">OS_MKDIR("C:\EXAMPLES\03192015")</syntaxhighlight>

=={{header|F_Sharp|F#}}==
<p>The library function System.IO.Directory.CreateDirectory also returns a DirectoryInfo
object of the deepest directory in the path.</p>
<p>In the F# REPL:</p>
{{out}}
<pre>
> System.IO.Directory.CreateDirectory (System.IO.Directory.GetCurrentDirectory())
;;
val it : System.IO.DirectoryInfo =
Temp {Attributes = Directory;
CreationTime = 2016-06-01 04:12:25;
CreationTimeUtc = 2016-06-01 02:12:25;
Exists = true;
Extension = "";
FullName = "C:\Users\Kai\AppData\Local\Temp";
LastAccessTime = 2016-08-18 20:42:21;
LastAccessTimeUtc = 2016-08-18 18:42:21;
LastWriteTime = 2016-08-18 20:42:21;
LastWriteTimeUtc = 2016-08-18 18:42:21;
Name = "Temp";
Parent = Local;
Root = C:\;}
> </pre>

=={{header|Factor}}==
The <code>make-directories</code> word performs this task. Note the value of <code>current-directory</code> is used as the base directory if a relative pathname is given.
<syntaxhighlight lang="factor">USE: io.directories
"path/to/dir" make-directories</syntaxhighlight>
The implementation of <code>make-directories</code>:
<syntaxhighlight lang="factor">USING: combinators.short-circuit io.backend io.files
io.pathnames kernel sequences ;
IN: io.directories
: make-directories ( path -- )
normalize-path trim-tail-separators dup
{ [ "." = ] [ root-directory? ] [ empty? ] [ exists? ] } 1||
[ make-parent-directories dup make-directory ] unless drop ;</syntaxhighlight>



=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#ifdef __FB_WIN32__
Dim pathname As String = "Ring\docs"
#else
Dim pathname As String = "Ring/docs"
#endif

Dim As String mkpathname = "mkdir " & pathname
Dim result As Long = Shell (mkpathname)

If result = 0 Then
Print "Created the directory..."
Chdir(pathname)
Print Curdir
Else
Print "error: unable to create folder " & pathname & " in the current path."
End If
Sleep</syntaxhighlight>

=={{header|FutureBasic}}==
==={{header|FileManager}}===
<syntaxhighlight lang="futurebasic">
void local fn MakeDirectoryPath
CFStringRef path = fn StringByExpandingTildeInPath( @"~/Desktop/FirstDir/SecondDir" )
fn FileManagerCreateDirectoryAtURL( fn URLFileURLWithPath(path), YES, NULL )
end fn

fn MakeDirectoryPath

HandleEvents
</syntaxhighlight>

==={{header|UNIX}}===
<syntaxhighlight lang="futurebasic">
void local fn MakeDirectoryPath
Str255 cmd
cmd = "mkdir -p " + fn StringPascalString( fn StringByExpandingTildeInPath( @"~/Desktop/FirstDir/SecondDir" ) )
open "UNIX", 2, cmd
end fn

fn MakeDirectoryPath

HandleEvents
</syntaxhighlight>

==={{header|UNIX via Task}}===
<syntaxhighlight lang="futurebasic">
void local fn MakeDirectoryPath
TaskRef task = fn TaskInit
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"bin/mkdir" ) )
TaskSetArguments( task, @[@"-p",fn StringByExpandingTildeInPath( @"~/Desktop/FirstDir/SecondDir" )] )
fn TaskLaunch( task, NULL )
end fn

fn MakeDirectoryPath

HandleEvents
</syntaxhighlight>


=={{header|Gambas}}==
<syntaxhighlight lang="gambas">Public Sub Form_Open()

If Not Exist(User.home &/ "TestFolder") Then Mkdir User.Home &/ "TestFolder"

End</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
The standard packages include <tt>[http://golang.org/pkg/os/#MkdirAll os.MkdirAll]</tt> which does exactly this
The standard packages include <tt>[http://golang.org/pkg/os/#MkdirAll os.MkdirAll]</tt> which does exactly this
(and its source is also available via that link).
(and its source is also available via that link).
<lang go> os.MkdirAll("/tmp/some/path/to/dir", 0770)</lang>
<syntaxhighlight lang="go"> os.MkdirAll("/tmp/some/path/to/dir", 0770)</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
import System.Directory (createDirectory, setCurrentDirectory)
import System.Directory (createDirectory, setCurrentDirectory)
import Data.List.Split (splitOn)
import Data.List.Split (splitOn)
Line 103: Line 420:
let path = splitOn "/" "path/to/dir"
let path = splitOn "/" "path/to/dir"
mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path
mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
Line 109: Line 426:
The verb <code>pathcreate</code> in the addon package [http://www.jsoftware.com/jwiki/Addons/general/dirutils general/dirutils] will create any non-existing directories in a path. It works on Windows, Linux and OS X.
The verb <code>pathcreate</code> in the addon package [http://www.jsoftware.com/jwiki/Addons/general/dirutils general/dirutils] will create any non-existing directories in a path. It works on Windows, Linux and OS X.
<lang J>require 'general/dirutils'
<syntaxhighlight lang="j">require 'general/dirutils'
pathcreate '/tmp/some/path/to/dir'</lang>
pathcreate '/tmp/some/path/to/dir'</syntaxhighlight>


Code is similar to the following:
Code is similar to the following:
<lang J>pathcreate=: monad define
<syntaxhighlight lang="j">pathcreate=: monad define
todir=. termsep_j_ jpathsep y
todir=. termsep_j_ jpathsep y
todirs=. }. ,each /\ <;.2 todir NB. base dirs
todirs=. }. ,each /\ <;.2 todir NB. base dirs
Line 129: Line 446:
)
)


direxist=: 2 = ftype&>@:boxopen</lang>
direxist=: 2 = ftype&>@:boxopen</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
The Java method for this is ''mkdirs'' and can be found in java.io.File. The source is in the ''src.zip'' of the JDK root directory.
The Java method for this is ''mkdirs'' and can be found in java.io.File. The source is in the ''src.zip'' of the JDK root directory.
<lang java>import java.io.File;
<syntaxhighlight lang="java">import java.io.File;


public interface Test {
public interface Test {
Line 146: Line 463:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 153: Line 470:
Simplified version of the popular [https://www.npmjs.org/package/mkdirp mkdirp library]:
Simplified version of the popular [https://www.npmjs.org/package/mkdirp mkdirp library]:


<lang Javascript>var path = require('path');
<syntaxhighlight lang="javascript">var path = require('path');
var fs = require('fs');
var fs = require('fs');


Line 179: Line 496:
}
}
});
});
}</lang>
}</syntaxhighlight>


=={{header|Mathematica}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}

<syntaxhighlight lang="julia">mkpath("/tmp/unusefuldir/helloworld.d/test123")</syntaxhighlight>

=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6

import java.io.File

fun main(args: Array<String>) {
// using built-in mkdirs() method
val success = File("./path/to/dir").mkdirs()
if (success) println("Directory path was created successfully")
else println("Failed to create directory path")
}</syntaxhighlight>

{{out}}
<pre>
Directory path was created successfully
</pre>

=={{header|Lua}}==
The ubiquitous luafilesystem module contains lfs.mkdir but this does not have an option equivalent to the posix mkdir -p.
Instead, the function shown here uses package.config to determine the correct directory separator for the OS and then iterates over the path string to create each individual folder in turn.
<syntaxhighlight lang="lua">require("lfs")

function mkdir (path)
local sep, pStr = package.config:sub(1, 1), ""
for dir in path:gmatch("[^" .. sep .. "]+") do
pStr = pStr .. dir .. sep
lfs.mkdir(pStr)
end
end

mkdir("C:\\path\\to\\dir") -- Quoting backslashes requires escape sequence</syntaxhighlight>
Note that attempting to run lfs.mkdir for a path that already exists writes no changes to disk and returns nil.

=={{header|Mathematica}}/{{header|Wolfram Language}}==
Creates directory specified by path, creating intermediate directories as necessary, and never fails if path already exists.
Creates directory specified by path, creating intermediate directories as necessary, and never fails if path already exists.
<lang Mathematica>mkdirp[path_] := Quiet[CreateDirectory[path,{CreateIntermediateDirectories->True}],{CreateDirectory::filex}]</lang>
<syntaxhighlight lang="mathematica">mkdirp[path_] := Quiet[CreateDirectory[path,{CreateIntermediateDirectories->True}],{CreateDirectory::filex}]</syntaxhighlight>


=={{header|Perl}}==
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">(define (mkdir-p mypath)
(if (= "/" (mypath 0)) ;; Abs or relative path?
(setf /? "/")
(setf /? "")
)
(setf path-components (clean empty? (parse mypath "/"))) ;; Split path and remove empty elements
(for (x 0 (length path-components))
(setf walking-path (string /? (join (slice path-components 0 (+ 1 x)) "/")))
(make-dir walking-path)
)
)


;; Using user-made function...
Using the File::Path core module:
(mkdir-p "/tmp/rosetta/test1")


;; ... or calling OS command directly.
<lang perl>use File::Path qw(make_path);
(! "mkdir -p /tmp/rosetta/test2")
(exit)</syntaxhighlight>


=={{header|Nim}}==
make_path('path/to/dir')</lang>
Note that the procedure "createDir" used here doesn’t raise an exception if the directory already exists because for current situations this is not an error. An exception is raised if the directory doesn’t exist after the call, if, for instance, permission is not allowed to create the directory.
<syntaxhighlight lang="nim">import os


try:
=={{header|Perl 6}}==
createDir("./path/to/dir")
echo "Directory now exists."
except OSError:
echo "Failed to create the directory."</syntaxhighlight>


=={{header|Objeck}}==
There is a built-in function for this:
<syntaxhighlight lang="objeck">class Program {
function : Main(args : String[]) ~ Nil {
System.IO.File.Directory->CreatePath("your/path/name")->PrintLine();
}
}</syntaxhighlight>


<lang perl6>mkpath 'path/to/dir'</lang>


=={{header|OCaml}}==
(<code>mkdir</code> also exists as a built-in function, but does not create nested subdirectories).

<syntaxhighlight lang="ocaml">let rec mkdir_p path perm =
if path <> "" then
try Unix.mkdir path perm with
| Unix.Unix_error (EEXIST, _, _) when Sys.is_directory path -> ()
| Unix.Unix_error (ENOENT, _, _) ->
mkdir_p (Filename.dirname path) perm;
Unix.mkdir path perm</syntaxhighlight>Requires the standard <code>[https://ocaml.org/manual/libunix.html unix]</code> library

=={{header|Perl}}==

Using the File::Path core module:

<syntaxhighlight lang="perl">use File::Path qw(make_path);

make_path('path/to/dir')</syntaxhighlight>

=={{header|Phix}}==
There's a builtin for that
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">create_directory</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"myapp/interface/letters"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Filesystem problem - could not create the new folder"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
The implementation in builtins/pfile.e is as follows (see there for initf() etc):
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">create_directory</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0o700</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">make_parent</span><span style="color: #0000FF;">=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">finit</span> <span style="color: #008080;">then</span> <span style="color: #000000;">initf</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">name</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">name</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_proper_path</span><span style="color: #0000FF;">(</span><span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Remove any trailing slash.</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">[$]=</span><span style="color: #004600;">SLASH</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">make_parent</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rfind</span><span style="color: #0000FF;">(</span><span style="color: #004600;">SLASH</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">parent</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">file_exists</span><span style="color: #0000FF;">(</span><span style="color: #000000;">parent</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">file_type</span><span style="color: #0000FF;">(</span><span style="color: #000000;">parent</span><span style="color: #0000FF;">)==</span><span style="color: #004600;">FILETYPE_DIRECTORY</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">create_directory</span><span style="color: #0000FF;">(</span><span style="color: #000000;">parent</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">make_parent</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">ret</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">LINUX</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">ret</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xCreateDirectory</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">ret</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">c_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xCreateDirectory</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">ret</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
Of course you could also use system("mkdir -p path/to/dir") or whatever.

=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(call "mkdir" "-p" "path/to/dir")</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue
New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
from errno import EEXIST
from errno import EEXIST
from os import mkdir, curdir
from os import mkdir, curdir
Line 231: Line 681:
if e.errno != EEXIST:
if e.errno != EEXIST:
raise
raise
</syntaxhighlight>
</lang>


Above is a modified version of the standard library's <code>os.makedirs</code>, for pedagogical purposes. In practice, you would be more likely to use the standard library call:
Above is a modified version of the standard library's <code>os.makedirs</code>, for pedagogical purposes. In practice, you would be more likely to use the standard library call:


<syntaxhighlight lang="python">
<lang Python>
def mkdirp(path):
def mkdirp(path):
try:
try:
Line 243: Line 693:
pass
pass
else: raise
else: raise
</syntaxhighlight>
</lang>


In Python3 this becomes even simpler:
In Python3 this becomes even simpler:


<syntaxhighlight lang="python">
<lang Python>
def mkdirp(path):
def mkdirp(path):
os.makedirs(path, exist_ok=True)
os.makedirs(path, exist_ok=True)
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 262: Line 712:
</blockquote>
</blockquote>


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define path-str "/tmp/woo/yay")
(define path-str "/tmp/woo/yay")
(define path/..-str "/tmp/woo")
(define path/..-str "/tmp/woo")
Line 283: Line 733:
(make-directory* path-str)
(make-directory* path-str)


(report-path-exists)</lang>
(report-path-exists)</syntaxhighlight>


{{out}}
{{out}}
Line 293: Line 743:


</pre>
</pre>

=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016.06}}

There is a built-in function for this:

<syntaxhighlight lang="raku" line>mkdir 'path/to/dir'</syntaxhighlight>

Alternatively, a custom solution (as per task description) that only uses the built-in <tt>mkdir</tt> non-recursively. The "triangle reduce" meta-operator <code>[\ ]</code> is used get the intermediate results of a left fold with the comma operator on the list of path elements.

<syntaxhighlight lang="raku" line>for [\,] $*SPEC.splitdir("../path/to/dir") -> @path {
mkdir $_ unless .e given $*SPEC.catdir(@path).IO;
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 300: Line 764:


Usage note: &nbsp; without the error messages being suppressed, the &nbsp; '''MKDIR''' &nbsp; command will issue an error message if the subdirectory (or its path) already exists.
Usage note: &nbsp; without the error messages being suppressed, the &nbsp; '''MKDIR''' &nbsp; command will issue an error message if the subdirectory (or its path) already exists.
<lang rexx>/*REXX program creates a directory and all its parent paths as necessary*/
<syntaxhighlight lang="rexx">/*REXX program creates a directory (folder) and all its parent paths as necessary. */
trace off /*suppress possible warning msgs.*/
trace off /*suppress possible warning msgs.*/

dPath = 'path\to\dir'
'MKDIR' dPath "2>nul" /*alias could be used: MD Dpath */
dPath = 'path\to\dir' /*define directory (folder) path.*/

/*stick a fork in it, we're done.*/</lang>
'MKDIR' dPath "2>nul" /*alias could be used: MD dPath */
/*stick a fork in it, we're done.*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
System("mkdir C:\Ring\docs")
System("mkdir C:\Ring\docs")
isdir("C:\Ring\docs")
isdir("C:\Ring\docs")
Line 319: Line 785:
return false
return false
done
done
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'fileutils'
<syntaxhighlight lang="ruby">require 'fileutils'
FileUtils.mkdir_p("path/to/dir") </lang>
FileUtils.mkdir_p("path/to/dir") </syntaxhighlight>
mkdir_p also takes an array of pathnames instead of a single pathname as an argument.
mkdir_p also takes an array of pathnames instead of a single pathname as an argument.
mkdir_p is aliased as: mkpath, makedirs.
mkdir_p is aliased as: mkpath, makedirs.

=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">
files #f, "c:\myDocs" ' check for directory
if #f hasanswer() then
if #f isDir() then ' is it a file or a directory
print "A directory exist"
else
print "A file exist"
end if
else
shell$("mkdir c:\myDocs" ' if not exist make a directory
end if</syntaxhighlight>
The following info about files / directory
FILE ACCESSOR methods
#handle HASANSWER() - Return non-zero if the file accessor has at least one
resulting row.
#handle ROWCOUNT() - Return the number of rows returned.
#handle NEXTFILE$() - Advance to the next row and return a comma delimited string for the next file (name, size, date, time, directory flag).
#handle NEXTFILE$([delimExpr$]) - Like NEXTFILE$() but you get to specify the delimiter instead of a comma.
#handle NAME$() - Return the name of the current file row.
#handle SIZE() - Return the size of the current file row.
#handle DATE$() - Return a string containing a formatted date for the current file row.
#handle TIME$() - Return a string containing a formatted time for the current file row.
#handle ISDIR() - Return non-zero if the current file row represents a directory instead of a file.
#handle RESET() - Reset the file accessor back to the beginning so you can read through them again.
#handle DATEFORMAT(template$) - Set the date format using a "mmm dd, yyyy" style template$.
#handle TIMEFORMAT(template$) - Set the time format using a "hh:mm:ss" style template$.
#handle ISNULL() - Returns zero (or false)
#handle DEBUG$() - Returns the string "Files"

=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::fs;

fn main() {
fs::create_dir_all("./path/to/dir").expect("An Error Occured!")
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>new java.io.File("/path/to/dir").mkdirs</lang>
<syntaxhighlight lang="scala">new java.io.File("/path/to/dir").mkdirs</syntaxhighlight>
Alternative (platform-independent) for the library function:
Alternative (platform-independent) for the library function:
<lang Scala>import java.io.File
<syntaxhighlight lang="scala">import java.io.File


def mkdirs(path: List[String]) = // return true if path was created
def mkdirs(path: List[String]) = // return true if path was created
Line 336: Line 839:


mkdirs(List("/path", "to", "dir"))
mkdirs(List("/path", "to", "dir"))
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 342: Line 845:
defines the function doMkdirCmd, which is used below.
defines the function doMkdirCmd, which is used below.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "cli_cmds.s7i";
include "cli_cmds.s7i";


Line 348: Line 851:
begin
begin
doMkdirCmd(argv(PROGRAM), TRUE);
doMkdirCmd(argv(PROGRAM), TRUE);
end func;</lang>
end func;</syntaxhighlight>


The library cli_cmds.s7i defines also
The library cli_cmds.s7i defines also
Line 357: Line 860:
The function doMkdir is used in the alternate solution below:
The function doMkdir is used in the alternate solution below:


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "cli_cmds.s7i";
include "cli_cmds.s7i";


Line 366: Line 869:
parameters := join(argv(PROGRAM), " ");
parameters := join(argv(PROGRAM), " ");
doMkdir(parameters);
doMkdir(parameters);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>Dir.new(Dir.cwd, "path", "to", "dir").make_path; # works cross-platform</lang>
<syntaxhighlight lang="ruby">Dir.new(Dir.cwd, "path", "to", "dir").make_path; # works cross-platform</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl's built in <code>file mkdir</code> works exactly this way:
Tcl's built in <code>file mkdir</code> works exactly this way:
<lang tcl>file mkdir ./path/to/dir</lang>
<syntaxhighlight lang="tcl">file mkdir ./path/to/dir</syntaxhighlight>
If a directory cannot be made (e.g., because it would involve making a directory with the same name as an existing file) the command will throw a trappable error, as normal for Tcl commands.
If a directory cannot be made (e.g., because it would involve making a directory with the same name as an existing file) the command will throw a trappable error, as normal for Tcl commands.


Line 379: Line 882:
{{works with|Bourne Again SHell}}
{{works with|Bourne Again SHell}}


<lang bash>function mkdirp() { mkdir -p "$1"; }</lang>
<syntaxhighlight lang="bash">function mkdirp() { mkdir -p "$1"; }</syntaxhighlight>

=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1

Sub Main()
System.IO.Directory.CreateDirectory("some/where")
End Sub

End Module</syntaxhighlight>

=={{header|Wren}}==
{{libheader|DOME}}
Curiously, this can only be done at present from a DOME program. A minimal script to do it would be:
<syntaxhighlight lang="wren">import "io" for FileSystem

class Main {
construct new() {}

init() {
FileSystem.createDirectory("path/to/dir")
}

update() {}

draw(alpha) {}
}

var Game = Main.new()</syntaxhighlight>
<br>
However, this functionality is expected to be added to Wren-cli in the next version. The code needed will be as follows:
<syntaxhighlight lang="wren">import "io" for Directory

Directory.create("path/to/dir")</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
This is for Unix as zkl doesn't have a built in mkdir method.
This is for Unix as zkl doesn't have a built in mkdir method.
<lang zkl>System.cmd("mkdir -p ../foo/bar")</lang>
<syntaxhighlight lang="zkl">System.cmd("mkdir -p ../foo/bar")</syntaxhighlight>
The system error code is returned (0 in this case).
The system error code is returned (0 in this case).
<lang zkl>fcn mkdir(path) { System.cmd("mkdir -p "+path) }</lang>
<syntaxhighlight lang="zkl">fcn mkdir(path) { System.cmd("mkdir -p "+path) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 18:50, 17 February 2024

Task
Make directory path
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Create a directory and any missing parents.

This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.

Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return successfully. Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).

It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.

11l

fs:create_dirs(path)

Ada

with Ada.Command_Line;
with Ada.Directories;
with Ada.Text_IO;

procedure Make_Directory_Path is
begin
   if Ada.Command_Line.Argument_Count /= 1 then
      Ada.Text_IO.Put_Line ("Usage: make_directory_path <path/to/dir>");
      return;
   end if;

   declare
      Path : String renames Ada.Command_Line.Argument (1);
   begin
      Ada.Directories.Create_Path (Path);
   end;
end Make_Directory_Path;

Aime

void
mkdirp(text path)
{
    list l;
    text p, s;

    file().b_affix(path).news(l, 0, 0, "/");

    for (, s in l) {
        p = p + s + "/";
        trap_q(mkdir, p, 00755);
    }
}

integer
main(void)
{
    mkdirp("./path/to/dir");

    0;
}

AppleScript

AppleScript is not a cross-platform language so this is a macOS-only solution. In post-Yosemite AppleScript we can draw on the macOS Foundation classes, which include the NSFileManager method: `createDirectoryAtPath:withIntermediateDirectories:attributes:error:`

use framework "Foundation"
use scripting additions


-- createOrFindDirectoryMay :: Bool -> FilePath -> Maybe IO ()
on createOrFindDirectoryMay(fp)
    createDirectoryIfMissingMay(true, fp)
end createOrFindDirectoryMay


-- createDirectoryIfMissingMay :: Bool -> FilePath -> Maybe IO ()
on createDirectoryIfMissingMay(blnParents, fp)
    if doesPathExist(fp) then
        nothing("Directory already exists: " & fp)
    else
        set e to reference
        set ca to current application
        set oPath to (ca's NSString's stringWithString:(fp))'s ¬
            stringByStandardizingPath
        set {bool, nse} to ca's NSFileManager's ¬
            defaultManager's createDirectoryAtPath:(oPath) ¬
            withIntermediateDirectories:(blnParents) ¬
            attributes:(missing value) |error|:(e)
        if bool then
            just(fp)
        else
            nothing((localizedDescription of nse) as string)
        end if
    end if
end createDirectoryIfMissingMay

-- TEST ----------------------------------------------------------------------
on run
    
    createOrFindDirectoryMay("~/Desktop/Notes/today")
    
end run

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- doesPathExist :: FilePath -> IO Bool
on doesPathExist(strPath)
    set ca to current application
    ca's NSFileManager's defaultManager's ¬
        fileExistsAtPath:((ca's NSString's ¬
            stringWithString:strPath)'s ¬
            stringByStandardizingPath)
end doesPathExist

-- just :: a -> Just a
on just(x)
    {nothing:false, just:x}
end just

-- nothing :: () -> Nothing
on nothing(msg)
    {nothing:true, msg:msg}
end nothing

Arturo

write.directory "path/to/some/directory" ø

AWK

# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
BEGIN {
    for (i=1; i<=ARGC-1; i++) {
      path = ARGV[i]
      msg = (make_dir_path(path) == 0) ? "created" : "exists"
      printf("'%s' %s\n",path,msg)
    }
    exit(0)
}
function make_dir_path(path,  cmd) {
#   cmd = sprintf("mkdir -p '%s'",path) # Unix
    cmd = sprintf("MKDIR \"%s\" 2>NUL",path) # MS-Windows
    return system(cmd)
}

sample command and output under Windows 8:

GAWK -f MAKE_DIRECTORY_PATH.AWK \TEMP\A \TEMP\A "\TEMP\A\B C"

'\TEMP\A' created
'\TEMP\A' exists
'\TEMP\A\B C' created

C

#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

int main (int argc, char **argv) {
    char *str, *s;
    struct stat statBuf;

    if (argc != 2) {
        fprintf (stderr, "usage: %s <path>\n", basename (argv[0]));
        exit (1);
    }
    s = argv[1];
    while ((str = strtok (s, "/")) != NULL) {
        if (str != s) {
            str[-1] = '/';
        }
        if (stat (argv[1], &statBuf) == -1) {
            mkdir (argv[1], 0);
        } else {
            if (! S_ISDIR (statBuf.st_mode)) {
                fprintf (stderr, "couldn't create directory %s\n", argv[1]);
                exit (1);
            }
        }
        s = NULL;
    }
    return 0;
}

C#

System.IO.Directory.CreateDirectory(path)

C++

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
	if(argc != 2)
	{
		std::cout << "usage: mkdir <path>\n";
		return -1;
	}

	fs::path pathToCreate(argv[1]);

	if (fs::exists(pathToCreate))
		return 0;

	if (fs::create_directories(pathToCreate))
		return 0;
	else
	{
		std::cout << "couldn't create directory: " << pathToCreate.string() << std::endl;
		return -1;
	}
}

Clojure

(defn mkdirp [path]
  (let [dir (java.io.File. path)]
    (if (.exists dir)
      true
      (.mkdirs dir))))

Common Lisp

(ensure-directories-exist "your/path/name")

D

import std.stdio;

void main() {
    makeDir("parent/test");
}

/// Manual implementation of what mkdirRecurse in std.file does.
void makeDir(string path) out {
    import std.exception : enforce;
    import std.file : exists;
    enforce(path.exists, "Failed to create the requested directory.");
} body {
    import std.array : array;
    import std.file;
    import std.path : pathSplitter, chainPath;

    auto workdir = "";
    foreach (dir; path.pathSplitter) {
        workdir = chainPath(workdir, dir).array;
        if (workdir.exists) {
            if (!workdir.isDir) {
                import std.conv : text;
                throw new FileException(text("The file ", workdir, " in the path ", path, " is not a directory."));
            }
        } else {
            workdir.mkdir();
        }
    }
}

Delphi

program Make_directory_path;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IOUtils;

const
  Path1 = '.\folder1\folder2\folder3'; // windows relative path (others OS formats are acepted)
  Path2 = 'folder4\folder5\folder6';

begin
  // "ForceDirectories" work with relative path if start with "./"
  if ForceDirectories(Path1) then
    Writeln('Created "', path1, '" sucessfull.');

  // "TDirectory.CreateDirectory" work with any path format
  //  but don't return sucess, requere "TDirectory.Exists" to check
  TDirectory.CreateDirectory(Path2);
  if TDirectory.Exists(Path2) then
    Writeln('Created "', path2, '" sucessfull.');
  Readln;
end.

Elixir

Tries to create the directory `path`. Missing parent directories are created.

File.mkdir_p("./path/to/dir")

ERRE

ERRE has the procedure "OS_MKDIR" in PC.LIB standard library, that creates a directory with all missing parents. Existing directory are simply ignored.

OS_MKDIR("C:\EXAMPLES\03192015")

F#

The library function System.IO.Directory.CreateDirectory also returns a DirectoryInfo object of the deepest directory in the path.

In the F# REPL:

Output:
> System.IO.Directory.CreateDirectory (System.IO.Directory.GetCurrentDirectory())
;;
val it : System.IO.DirectoryInfo =
  Temp {Attributes = Directory;
        CreationTime = 2016-06-01 04:12:25;
        CreationTimeUtc = 2016-06-01 02:12:25;
        Exists = true;
        Extension = "";
        FullName = "C:\Users\Kai\AppData\Local\Temp";
        LastAccessTime = 2016-08-18 20:42:21;
        LastAccessTimeUtc = 2016-08-18 18:42:21;
        LastWriteTime = 2016-08-18 20:42:21;
        LastWriteTimeUtc = 2016-08-18 18:42:21;
        Name = "Temp";
        Parent = Local;
        Root = C:\;}
> 

Factor

The make-directories word performs this task. Note the value of current-directory is used as the base directory if a relative pathname is given.

USE: io.directories
"path/to/dir" make-directories

The implementation of make-directories:

USING: combinators.short-circuit io.backend io.files
io.pathnames kernel sequences ;
IN: io.directories
: make-directories ( path -- )
    normalize-path trim-tail-separators dup
    { [ "." = ] [ root-directory? ] [ empty? ] [ exists? ] } 1||
    [ make-parent-directories dup make-directory ] unless drop ;


FreeBASIC

#ifdef __FB_WIN32__
    Dim pathname As String = "Ring\docs"
#else
    Dim pathname As String = "Ring/docs"
#endif

Dim As String mkpathname = "mkdir " & pathname
Dim result As Long = Shell (mkpathname)

If result = 0 Then
    Print "Created the directory..."
    Chdir(pathname)
    Print Curdir
Else
    Print "error: unable to create folder " & pathname & " in the current path."
End If
Sleep

FutureBasic

FileManager

void local fn MakeDirectoryPath
  CFStringRef path = fn StringByExpandingTildeInPath( @"~/Desktop/FirstDir/SecondDir" )
  fn FileManagerCreateDirectoryAtURL( fn URLFileURLWithPath(path), YES, NULL )
end fn

fn MakeDirectoryPath

HandleEvents

UNIX

void local fn MakeDirectoryPath
  Str255 cmd
  cmd = "mkdir -p " + fn StringPascalString( fn StringByExpandingTildeInPath( @"~/Desktop/FirstDir/SecondDir" ) )
  open "UNIX", 2, cmd
end fn

fn MakeDirectoryPath

HandleEvents

UNIX via Task

void local fn MakeDirectoryPath
  TaskRef task = fn TaskInit
  TaskSetExecutableURL( task, fn URLFileURLWithPath( @"bin/mkdir" ) )
  TaskSetArguments( task, @[@"-p",fn StringByExpandingTildeInPath( @"~/Desktop/FirstDir/SecondDir" )] )
  fn TaskLaunch( task, NULL )
end fn

fn MakeDirectoryPath

HandleEvents


Gambas

Public Sub Form_Open()

If Not Exist(User.home &/ "TestFolder") Then Mkdir User.Home &/ "TestFolder"

End

Go

The standard packages include os.MkdirAll which does exactly this (and its source is also available via that link).

	os.MkdirAll("/tmp/some/path/to/dir", 0770)

Haskell

import System.Directory (createDirectory, setCurrentDirectory)
import Data.List.Split  (splitOn)

main :: IO ()
main = do
  let path = splitOn "/" "path/to/dir"
  mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path

J

The verb pathcreate in the addon package general/dirutils will create any non-existing directories in a path. It works on Windows, Linux and OS X.

require 'general/dirutils'
pathcreate '/tmp/some/path/to/dir'

Code is similar to the following:

pathcreate=: monad define
  todir=. termsep_j_ jpathsep y
  todirs=. }. ,each /\ <;.2 todir  NB. base dirs
  msk=. -.direxist todirs          NB. 1 for each non-existing dir
  msk=. 0 (i. msk i: 0)}msk
  dircreate msk#todirs             NB. create non-existing base dirs
)

dircreate=: monad define
  y=. boxxopen y
  msk=. -.direxist y
  if. ''-:$msk do. msk=. (#y)#msk end.
  res=. 1!:5 msk#y
  msk #inv ,res
)

direxist=: 2 = ftype&>@:boxopen

Java

The Java method for this is mkdirs and can be found in java.io.File. The source is in the src.zip of the JDK root directory.

import java.io.File;

public interface Test {

    public static void main(String[] args) {
        try {
            File f = new File("C:/parent/test");
            if (f.mkdirs())
                System.out.println("path successfully created");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

JavaScript

Works with: Node.js

Simplified version of the popular mkdirp library:

var path = require('path');
var fs = require('fs');

function mkdirp (p, cb) {
    cb = cb || function () {};
    p = path.resolve(p);

    fs.mkdir(p, function (er) {
        if (!er) {
            return cb(null);
        }
        switch (er.code) {
            case 'ENOENT':
                // The directory doesn't exist. Make its parent and try again.
                mkdirp(path.dirname(p), function (er) {
                    if (er) cb(er);
                    else mkdirp(p, cb);
                });
                break;

                // In the case of any other error, something is borked.
            default:
                cb(er);
                break;
        }
    });
}

Julia

Works with: Julia version 0.6
mkpath("/tmp/unusefuldir/helloworld.d/test123")

Kotlin

// version 1.0.6

import java.io.File

fun main(args: Array<String>) {
    // using built-in mkdirs() method
    val success = File("./path/to/dir").mkdirs()
    if (success) println("Directory path was created successfully")
    else         println("Failed to create directory path")
}
Output:
Directory path was created successfully

Lua

The ubiquitous luafilesystem module contains lfs.mkdir but this does not have an option equivalent to the posix mkdir -p. Instead, the function shown here uses package.config to determine the correct directory separator for the OS and then iterates over the path string to create each individual folder in turn.

require("lfs")

function mkdir (path)
  local sep, pStr = package.config:sub(1, 1), ""
  for dir in path:gmatch("[^" .. sep .. "]+") do
    pStr = pStr .. dir .. sep
    lfs.mkdir(pStr)
  end
end

mkdir("C:\\path\\to\\dir") -- Quoting backslashes requires escape sequence

Note that attempting to run lfs.mkdir for a path that already exists writes no changes to disk and returns nil.

Mathematica/Wolfram Language

Creates directory specified by path, creating intermediate directories as necessary, and never fails if path already exists.

mkdirp[path_] := Quiet[CreateDirectory[path,{CreateIntermediateDirectories->True}],{CreateDirectory::filex}]

NewLISP

(define (mkdir-p mypath)
    (if (= "/" (mypath 0)) ;; Abs or relative path?
        (setf /? "/")
        (setf /? "")
    )
    (setf path-components (clean empty? (parse mypath "/"))) ;; Split path and remove empty elements
    (for (x 0 (length path-components))
        (setf walking-path (string /? (join (slice path-components 0 (+ 1 x)) "/")))
        (make-dir walking-path)
    )
)

;; Using user-made function...
(mkdir-p "/tmp/rosetta/test1")

;; ... or calling OS command directly.
(! "mkdir -p /tmp/rosetta/test2")
(exit)

Nim

Note that the procedure "createDir" used here doesn’t raise an exception if the directory already exists because for current situations this is not an error. An exception is raised if the directory doesn’t exist after the call, if, for instance, permission is not allowed to create the directory.

import os

try:
  createDir("./path/to/dir")
  echo "Directory now exists."
except OSError:
  echo "Failed to create the directory."

Objeck

class Program {
  function : Main(args : String[]) ~ Nil {
    System.IO.File.Directory->CreatePath("your/path/name")->PrintLine();
  }
}


OCaml

let rec mkdir_p path perm =
 if path <> "" then
    try Unix.mkdir path perm with
    | Unix.Unix_error (EEXIST, _, _) when Sys.is_directory path -> ()
    | Unix.Unix_error (ENOENT, _, _) ->
      mkdir_p (Filename.dirname path) perm;
      Unix.mkdir path perm

Requires the standard unix library

Perl

Using the File::Path core module:

use File::Path qw(make_path);

make_path('path/to/dir')

Phix

There's a builtin for that

without js -- (file i/o)
if not create_directory("myapp/interface/letters") then
    crash("Filesystem problem - could not create the new folder")
end if

The implementation in builtins/pfile.e is as follows (see there for initf() etc):

global function create_directory(string name, integer mode=0o700, bool make_parent=true)

    if not finit then initf() end if

    assert(length(name)!=0)
    name = get_proper_path(name)

    -- Remove any trailing slash.
    if name[$]=SLASH then
        name = name[1..$-1]
    end if

    if make_parent then
        integer pos = rfind(SLASH, name)
        if pos!=0 then
            string parent = name[1..pos-1]
            if file_exists(parent) then
                assert(file_type(parent)==FILETYPE_DIRECTORY)
            else
                if not create_directory(parent, mode, make_parent) then
                    return 0
                end if
            end if
        end if
    end if

    bool ret
    if platform()=LINUX then

        ret = not c_func(xCreateDirectory, {name, mode})

    elsif platform()=WINDOWS then

        ret = c_func(xCreateDirectory, {name, 0})

    end if

    return ret
end function

Of course you could also use system("mkdir -p path/to/dir") or whatever.

PicoLisp

(call "mkdir" "-p" "path/to/dir")

PowerShell

New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue

Python

from errno import EEXIST
from os import mkdir, curdir
from os.path import split, exists

def mkdirp(path, mode=0777):
    head, tail = split(path)
    if not tail:
        head, tail = split(head)
    if head and tail and not exists(head):
        try:
            mkdirp(head, mode)
        except OSError as e:
            # be happy if someone already created the path
            if e.errno != EEXIST:
                raise
        if tail == curdir:  # xxx/newdir/. exists if xxx/newdir exists
            return
    try:
        mkdir(path, mode)
    except OSError as e:
        # be happy if someone already created the path
        if e.errno != EEXIST:
            raise

Above is a modified version of the standard library's os.makedirs, for pedagogical purposes. In practice, you would be more likely to use the standard library call:

def mkdirp(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else: raise

In Python3 this becomes even simpler:

def mkdirp(path):
    os.makedirs(path, exist_ok=True)

Racket

Uses make-directory* (NB the star — that causes the intermediate directories to be produced).

Canonical documentation at Racket Documentation for Filesystem

Creates directory specified by path, creating intermediate

directories as necessary, and never failing if path exists already.

#lang racket
(define path-str "/tmp/woo/yay")
(define path/..-str "/tmp/woo")

;; clean up from a previous run
(when (directory-exists? path-str)
  (delete-directory path-str)
  (delete-directory path/..-str))
;; delete-directory/files could also be used -- but that requires goggles and rubber
;; gloves to handle safely!

(define (report-path-exists)
  (printf "~s exists (as a directory?):~a~%~s exists (as a directory?):~a~%~%"
          path/..-str (directory-exists? path/..-str)
          path-str (directory-exists? path-str)))

(report-path-exists)

;; Really ... this is the only bit that matters!
(make-directory* path-str)

(report-path-exists)
Output:
"/tmp/woo" exists (as a directory?):#f
"/tmp/woo/yay" exists (as a directory?):#f

"/tmp/woo" exists (as a directory?):#t
"/tmp/woo/yay" exists (as a directory?):#t

Raku

(formerly Perl 6)

Works with: rakudo version 2016.06

There is a built-in function for this:

mkdir 'path/to/dir'

Alternatively, a custom solution (as per task description) that only uses the built-in mkdir non-recursively. The "triangle reduce" meta-operator [\ ] is used get the intermediate results of a left fold with the comma operator on the list of path elements.

for [\,] $*SPEC.splitdir("../path/to/dir") -> @path {
    mkdir $_ unless .e given $*SPEC.catdir(@path).IO;
}

REXX

The following works with any modern (Microsoft) Windows ® and/or DOS.

Operating system note:   all versions of Microsoft ® DOS require the use of a blackslash   [\]   instead of a forward slash   [/].

Usage note:   without the error messages being suppressed, the   MKDIR   command will issue an error message if the subdirectory (or its path) already exists.

/*REXX program  creates a  directory (folder)  and all its  parent paths  as necessary. */
trace off                                              /*suppress possible warning msgs.*/

dPath = 'path\to\dir'                                  /*define directory (folder) path.*/

'MKDIR'  dPath  "2>nul"                                /*alias could be used:  MD dPath */
                                                       /*stick a fork in it, we're done.*/

Ring

System("mkdir C:\Ring\docs")
isdir("C:\Ring\docs")

see isdir("C:\Ring\docs") + nl
func isdir cDir
     try
        dir(cDir)
        return true
     catch
        return false
     done

Ruby

require 'fileutils'
FileUtils.mkdir_p("path/to/dir")

mkdir_p also takes an array of pathnames instead of a single pathname as an argument. mkdir_p is aliased as: mkpath, makedirs.

Run BASIC

files #f, "c:\myDocs"		' check for directory
if #f hasanswer() then
   if #f isDir() then		' is it a file or a directory
    print "A directory exist"
    else
    print "A file exist"
   end if
 else
  shell$("mkdir c:\myDocs"    ' if not exist make a directory
end if

The following info about files / directory FILE ACCESSOR methods

  1. handle HASANSWER() - Return non-zero if the file accessor has at least one

resulting row.

  1. handle ROWCOUNT() - Return the number of rows returned.
  2. handle NEXTFILE$() - Advance to the next row and return a comma delimited string for the next file (name, size, date, time, directory flag).
  3. handle NEXTFILE$([delimExpr$]) - Like NEXTFILE$() but you get to specify the delimiter instead of a comma.
  4. handle NAME$() - Return the name of the current file row.
  5. handle SIZE() - Return the size of the current file row.
  6. handle DATE$() - Return a string containing a formatted date for the current file row.
  7. handle TIME$() - Return a string containing a formatted time for the current file row.
  8. handle ISDIR() - Return non-zero if the current file row represents a directory instead of a file.
  9. handle RESET() - Reset the file accessor back to the beginning so you can read through them again.
  10. handle DATEFORMAT(template$) - Set the date format using a "mmm dd, yyyy" style template$.
  11. handle TIMEFORMAT(template$) - Set the time format using a "hh:mm:ss" style template$.
  12. handle ISNULL() - Returns zero (or false)
  13. handle DEBUG$() - Returns the string "Files"

Rust

use std::fs;

fn main() {
    fs::create_dir_all("./path/to/dir").expect("An Error Occured!")
}

Scala

new java.io.File("/path/to/dir").mkdirs

Alternative (platform-independent) for the library function:

import java.io.File

def mkdirs(path: List[String]) = // return true if path was created
    path.tail.foldLeft(new File(path.head)){(a,b) => a.mkdir; new File(a,b)}.mkdir

mkdirs(List("/path", "to", "dir"))

Seed7

The library cli_cmds.s7i defines the function doMkdirCmd, which is used below.

$ include "seed7_05.s7i";
  include "cli_cmds.s7i";

const proc: main is func
  begin
    doMkdirCmd(argv(PROGRAM), TRUE);
  end func;

The library cli_cmds.s7i defines also doMkdir (Make directories like the Unix mkdir command) and doMd (Make directories like the DOS md command). This functions read the parameters and options from a string. The reading is done according to Unix respectively DOS/Windows rules. The function doMkdir is used in the alternate solution below:

$ include "seed7_05.s7i";
  include "cli_cmds.s7i";

const proc: main is func
  local
    var string: parameters is "";
  begin
    parameters := join(argv(PROGRAM), " ");
    doMkdir(parameters);
  end func;

Sidef

Dir.new(Dir.cwd, "path", "to", "dir").make_path;   # works cross-platform

Tcl

Tcl's built in file mkdir works exactly this way:

file mkdir ./path/to/dir

If a directory cannot be made (e.g., because it would involve making a directory with the same name as an existing file) the command will throw a trappable error, as normal for Tcl commands.

UNIX Shell

Works with: Bourne Again SHell
function mkdirp() { mkdir -p "$1"; }

Visual Basic .NET

Translation of: C#
Module Module1

    Sub Main()
        System.IO.Directory.CreateDirectory("some/where")
    End Sub

End Module

Wren

Library: DOME

Curiously, this can only be done at present from a DOME program. A minimal script to do it would be:

import "io" for FileSystem

class Main {
    construct new() {}

    init() {
        FileSystem.createDirectory("path/to/dir")
    }

    update() {}

    draw(alpha) {}
}

var Game = Main.new()


However, this functionality is expected to be added to Wren-cli in the next version. The code needed will be as follows:

import "io" for Directory

Directory.create("path/to/dir")

zkl

This is for Unix as zkl doesn't have a built in mkdir method.

System.cmd("mkdir -p ../foo/bar")

The system error code is returned (0 in this case).

fcn mkdir(path) { System.cmd("mkdir -p "+path) }
Output:
zkl: mkdir("../foo/bar")
0
zkl: mkdir("/foo/bar")
mkdir: cannot create directory ‘/foo’: Permission denied
256