Make directory path: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H (future CLI version)
m (→‎{{header|Phix}}: added syntax colouring, marked p2js incompatible)
m (→‎{{header|Wren}}: Changed to Wren S/H (future CLI version))
 
(5 intermediate revisions by 4 users not shown)
Line 14:
 
=={{header|11l}}==
<syntaxhighlight lang ="11l">fs:create_dirs(path)</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line;
with Ada.Directories;
with Ada.Text_IO;
Line 33:
Ada.Directories.Create_Path (Path);
end;
end Make_Directory_Path;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
mkdirp(text path)
{
Line 56:
 
0;
}</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 64:
`createDirectoryAtPath:withIntermediateDirectories:attributes:error:`
 
<langsyntaxhighlight AppleScriptlang="applescript">use framework "Foundation"
use scripting additions
 
Line 121:
on nothing(msg)
{nothing:true, msg:msg}
end nothing</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">write.directory "path/to/some/directory" ø</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
BEGIN {
Line 143:
return system(cmd)
}
</syntaxhighlight>
</lang>
<p>sample command and output under Windows 8:</p>
<pre>
Line 154:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
Line 185:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang ="csharp">System.IO.Directory.CreateDirectory(path)</langsyntaxhighlight>
 
=={{header|C++|CPP}}==
<langsyntaxhighlight lang="cpp">
#include <filesystem>
#include <iostream>
Line 218:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn mkdirp [path]
(let [dir (java.io.File. path)]
(if (.exists dir)
true
(.mkdirs dir))))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(ensure-directories-exist "your/path/name")
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 261:
}
}
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IOUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Make_directory_path;
 
Line 289:
Writeln('Created "', path2, '" sucessfull.');
Readln;
end.</langsyntaxhighlight>
 
=={{header|Elixir}}==
Tries to create the directory `path`. Missing parent directories are created.
<langsyntaxhighlight lang="elixir">File.mkdir_p("./path/to/dir")</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight ERRElang="erre">OS_MKDIR("C:\EXAMPLES\03192015")</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
Line 326:
=={{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.
<langsyntaxhighlight lang="factor">USE: io.directories
"path/to/dir" make-directories</langsyntaxhighlight>
The implementation of <code>make-directories</code>:
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit io.backend io.files
io.pathnames kernel sequences ;
IN: io.directories
Line 335:
normalize-path trim-tail-separators dup
{ [ "." = ] [ root-directory? ] [ empty? ] [ exists? ] } 1||
[ make-parent-directories dup make-directory ] unless drop ;</langsyntaxhighlight>
 
 
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#ifdef __FB_WIN32__
Dim pathname As String = "Ring\docs"
#else
Line 356:
Print "error: unable to create folder " & pathname & " in the current path."
End If
Sleep</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
 
If Not Exist(User.home &/ "TestFolder") Then Mkdir User.Home &/ "TestFolder"
 
End</langsyntaxhighlight>
 
=={{header|Go}}==
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).
<langsyntaxhighlight lang="go"> os.MkdirAll("/tmp/some/path/to/dir", 0770)</langsyntaxhighlight>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
import System.Directory (createDirectory, setCurrentDirectory)
import Data.List.Split (splitOn)
Line 380 ⟶ 420:
let path = splitOn "/" "path/to/dir"
mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path
</syntaxhighlight>
</lang>
 
=={{header|J}}==
Line 386 ⟶ 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.
<langsyntaxhighlight Jlang="j">require 'general/dirutils'
pathcreate '/tmp/some/path/to/dir'</langsyntaxhighlight>
 
Code is similar to the following:
<langsyntaxhighlight Jlang="j">pathcreate=: monad define
todir=. termsep_j_ jpathsep y
todirs=. }. ,each /\ <;.2 todir NB. base dirs
Line 406 ⟶ 446:
)
 
direxist=: 2 = ftype&>@:boxopen</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="java">import java.io.File;
 
public interface Test {
Line 423 ⟶ 463:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 430 ⟶ 470:
Simplified version of the popular [https://www.npmjs.org/package/mkdirp mkdirp library]:
 
<langsyntaxhighlight Javascriptlang="javascript">var path = require('path');
var fs = require('fs');
 
Line 456 ⟶ 496:
}
});
}</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">mkpath("/tmp/unusefuldir/helloworld.d/test123")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.io.File
Line 473 ⟶ 513:
if (success) println("Directory path was created successfully")
else println("Failed to create directory path")
}</langsyntaxhighlight>
 
{{out}}
Line 483 ⟶ 523:
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.
<langsyntaxhighlight Lualang="lua">require("lfs")
 
function mkdir (path)
Line 493 ⟶ 533:
end
 
mkdir("C:\\path\\to\\dir") -- Quoting backslashes requires escape sequence</langsyntaxhighlight>
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.
<langsyntaxhighlight Mathematicalang="mathematica">mkdirp[path_] := Quiet[CreateDirectory[path,{CreateIntermediateDirectories->True}],{CreateDirectory::filex}]</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">(define (mkdir-p mypath)
(if (= "/" (mypath 0)) ;; Abs or relative path?
(setf /? "/")
Line 518 ⟶ 558:
;; ... or calling OS command directly.
(! "mkdir -p /tmp/rosetta/test2")
(exit)</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight Nimlang="nim">import os
 
try:
Line 528 ⟶ 568:
echo "Directory now exists."
except OSError:
echo "Failed to create the directory."</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Program {
function : Main(args : String[]) ~ Nil {
System.IO.File.Directory->CreatePath("your/path/name")->PrintLine();
}
}</langsyntaxhighlight>
 
 
=={{header|OCaml}}==
 
<syntaxhighlight lang="ocaml">let rec mkdir_p path perm =
<lang ocaml>#load "unix.cma"
if path <> "" then
 
try Unix.mkdir thispath perm perms;with
let mkdir_p ~path ~perms =
| Unix.Unix_error (EEXIST, _, _) when Sys.is_directory path -> ()
let ps = String.split_on_char '/' path in
| Unix.Unix_error (ENOENT, _, _) ->
let rec aux acc = function [] -> ()
mkdir_p (Filename.dirname path) perm;
| p::ps ->
Unix.mkdir path perm</syntaxhighlight>Requires the standard <code>[https://ocaml.org/manual/libunix.html unix]</code> library
let this = String.concat Filename.dir_sep (List.rev (p::acc)) in
Unix.mkdir this perms;
aux (p::acc) ps
in
aux [] ps
 
let () =
mkdir_p "path/to/dir" 0o700</lang>
 
=={{header|Perl}}==
Line 559 ⟶ 592:
Using the File::Path core module:
 
<langsyntaxhighlight lang="perl">use File::Path qw(make_path);
 
make_path('path/to/dir')</langsyntaxhighlight>
 
=={{header|Phix}}==
There's a builtin for that
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
The implementation in builtins/pfile.e is as follows (see there for initf() etc):
<!--<langsyntaxhighlight Phixlang="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>
Line 612 ⟶ 645:
<span style="color: #008080;">return</span> <span style="color: #000000;">ret</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
Of course you could also use system("mkdir -p path/to/dir") or whatever.
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(call "mkdir" "-p" "path/to/dir")</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
from errno import EEXIST
from os import mkdir, curdir
Line 648 ⟶ 681:
if e.errno != EEXIST:
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:
 
<syntaxhighlight lang="python">
<lang Python>
def mkdirp(path):
try:
Line 660 ⟶ 693:
pass
else: raise
</syntaxhighlight>
</lang>
 
In Python3 this becomes even simpler:
 
<syntaxhighlight lang="python">
<lang Python>
def mkdirp(path):
os.makedirs(path, exist_ok=True)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 679 ⟶ 712:
</blockquote>
 
<langsyntaxhighlight lang="racket">#lang racket
(define path-str "/tmp/woo/yay")
(define path/..-str "/tmp/woo")
Line 700 ⟶ 733:
(make-directory* path-str)
 
(report-path-exists)</langsyntaxhighlight>
 
{{out}}
Line 717 ⟶ 750:
There is a built-in function for this:
 
<syntaxhighlight lang="raku" perl6line>mkdir 'path/to/dir'</langsyntaxhighlight>
 
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" perl6line>for [\,] $*SPEC.splitdir("../path/to/dir") -> @path {
mkdir $_ unless .e given $*SPEC.catdir(@path).IO;
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 731 ⟶ 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.
<langsyntaxhighlight lang="rexx">/*REXX program creates a directory (folder) and all its parent paths as necessary. */
trace off /*suppress possible warning msgs.*/
 
Line 737 ⟶ 770:
 
'MKDIR' dPath "2>nul" /*alias could be used: MD dPath */
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
System("mkdir C:\Ring\docs")
isdir("C:\Ring\docs")
Line 752 ⟶ 785:
return false
done
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'fileutils'
FileUtils.mkdir_p("path/to/dir") </langsyntaxhighlight>
mkdir_p also takes an array of pathnames instead of a single pathname as an argument.
mkdir_p is aliased as: mkpath, makedirs.
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">
files #f, "c:\myDocs" ' check for directory
if #f hasanswer() then
Line 771 ⟶ 804:
else
shell$("mkdir c:\myDocs" ' if not exist make a directory
end if</langsyntaxhighlight>
The following info about files / directory
FILE ACCESSOR methods
Line 791 ⟶ 824:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::fs;
 
fn main() {
fs::create_dir_all("./path/to/dir").expect("An Error Occured!")
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">new java.io.File("/path/to/dir").mkdirs</langsyntaxhighlight>
Alternative (platform-independent) for the library function:
<langsyntaxhighlight Scalalang="scala">import java.io.File
 
def mkdirs(path: List[String]) = // return true if path was created
Line 806 ⟶ 839:
 
mkdirs(List("/path", "to", "dir"))
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
Line 812 ⟶ 845:
defines the function doMkdirCmd, which is used below.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "cli_cmds.s7i";
 
Line 818 ⟶ 851:
begin
doMkdirCmd(argv(PROGRAM), TRUE);
end func;</langsyntaxhighlight>
 
The library cli_cmds.s7i defines also
Line 827 ⟶ 860:
The function doMkdir is used in the alternate solution below:
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "cli_cmds.s7i";
 
Line 836 ⟶ 869:
parameters := join(argv(PROGRAM), " ");
doMkdir(parameters);
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">Dir.new(Dir.cwd, "path", "to", "dir").make_path; # works cross-platform</langsyntaxhighlight>
 
=={{header|Tcl}}==
Tcl's built in <code>file mkdir</code> works exactly this way:
<langsyntaxhighlight lang="tcl">file mkdir ./path/to/dir</langsyntaxhighlight>
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 849 ⟶ 882:
{{works with|Bourne Again SHell}}
 
<langsyntaxhighlight lang="bash">function mkdirp() { mkdir -p "$1"; }</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 859 ⟶ 892:
End Sub
 
End Module</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|DOME}}
Curiously, this can only be done at present from a DOME program. A minimal script to do it would be:
<langsyntaxhighlight ecmascriptlang="wren">import "io" for FileSystem
 
class Main {
Line 878 ⟶ 911:
}
 
var Game = Main.new()</langsyntaxhighlight>
<br>
However, this functionality willis expected to be added to Wren-cli whenin versionthe 0.4.0next is officially releasedversion. The code needed will be as follows:
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Directory
 
Directory.create("path/to/dir")</langsyntaxhighlight>
 
=={{header|zkl}}==
This is for Unix as zkl doesn't have a built in mkdir method.
<langsyntaxhighlight lang="zkl">System.cmd("mkdir -p ../foo/bar")</langsyntaxhighlight>
The system error code is returned (0 in this case).
<langsyntaxhighlight lang="zkl">fcn mkdir(path) { System.cmd("mkdir -p "+path) }</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits