Make directory path: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H (future CLI version)
m (→{{header|Wren}}: Changed to Wren S/H (future CLI version)) |
|||
(19 intermediate revisions by 15 users not shown) | |||
Line 12:
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}}==
<
mkdirp(text path)
{
Line 34 ⟶ 56:
0;
}</
=={{header|AppleScript}}==
Line 42 ⟶ 64:
`createDirectoryAtPath:withIntermediateDirectories:attributes:error:`
<
use scripting additions
Line 99 ⟶ 121:
on nothing(msg)
{nothing:true, msg:msg}
end nothing</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">write.directory "path/to/some/directory" ø</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
BEGIN {
Line 117 ⟶ 143:
return system(cmd)
}
</syntaxhighlight>
<p>sample command and output under Windows 8:</p>
<pre>
Line 128 ⟶ 154:
=={{header|C}}==
<
#include <stdlib.h>
#include <libgen.h>
Line 159 ⟶ 185:
}
return 0;
}</
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">System.IO.Directory.CreateDirectory(path)</syntaxhighlight>
=={{header|C++|CPP}}==
<
#include <filesystem>
#include <iostream>
namespace fs = std
int main(int argc, char* argv[])
Line 189 ⟶ 218:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(let [dir (java.io.File. path)]
(if (.exists dir)
true
(.mkdirs dir))))</
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(ensure-directories-exist "your/path/name")
</syntaxhighlight>
=={{header|D}}==
<
void main() {
Line 234 ⟶ 261:
}
}
}</
=={{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}}==
Tries to create the directory `path`. Missing parent directories are created.
<
=={{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.
<
=={{header|F_Sharp|F#}}==
Line 268 ⟶ 323:
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}}==
<
If Not Exist(User.home &/ "TestFolder") Then Mkdir User.Home &/ "TestFolder"
End</
=={{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).
<
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
import System.Directory (createDirectory, setCurrentDirectory)
import Data.List.Split (splitOn)
Line 290 ⟶ 420:
let path = splitOn "/" "path/to/dir"
mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path
</syntaxhighlight>
=={{header|J}}==
Line 296 ⟶ 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.
<
pathcreate '/tmp/some/path/to/dir'</
Code is similar to the following:
<
todir=. termsep_j_ jpathsep y
todirs=. }. ,each /\ <;.2 todir NB. base dirs
Line 316 ⟶ 446:
)
direxist=: 2 = ftype&>@:boxopen</
=={{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.
<
public interface Test {
Line 333 ⟶ 463:
}
}
}</
=={{header|JavaScript}}==
Line 340 ⟶ 470:
Simplified version of the popular [https://www.npmjs.org/package/mkdirp mkdirp library]:
<
var fs = require('fs');
Line 366 ⟶ 496:
}
});
}</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
=={{header|Kotlin}}==
<
import java.io.File
Line 383 ⟶ 513:
if (success) println("Directory path was created successfully")
else println("Failed to create directory path")
}</
{{out}}
Line 393 ⟶ 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.
<
function mkdir (path)
Line 403 ⟶ 533:
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.
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Creates directory specified by path, creating intermediate directories as necessary, and never fails if path already exists.
<
=={{header|NewLISP}}==
<
(if (= "/" (mypath 0)) ;; Abs or relative path?
(setf /? "/")
Line 428 ⟶ 558:
;; ... or calling OS command directly.
(! "mkdir -p /tmp/rosetta/test2")
(exit)</
=={{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.
<syntaxhighlight lang="nim">import os
try:
createDir("./path/to/dir")
echo "Directory now exists."
except OSError:
echo "Failed to create the directory."</syntaxhighlight>
=={{header|Objeck}}==
<
function : Main(args : String[]) ~ Nil {
System.IO.File.Directory->CreatePath("your/path/name")->PrintLine();
}
}</
=={{header|OCaml}}==
<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);
=={{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}}==
<
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue
</syntaxhighlight>
=={{header|Python}}==
<syntaxhighlight lang="python">
from errno import EEXIST
from os import mkdir, curdir
Line 536 ⟶ 681:
if e.errno != EEXIST:
raise
</syntaxhighlight>
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">
def mkdirp(path):
try:
Line 548 ⟶ 693:
pass
else: raise
</syntaxhighlight>
In Python3 this becomes even simpler:
<syntaxhighlight lang="python">
def mkdirp(path):
os.makedirs(path, exist_ok=True)
</syntaxhighlight>
=={{header|Racket}}==
Line 567 ⟶ 712:
</blockquote>
<
(define path-str "/tmp/woo/yay")
(define path/..-str "/tmp/woo")
Line 588 ⟶ 733:
(make-directory* path-str)
(report-path-exists)</
{{out}}
Line 598 ⟶ 743:
</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}}==
Line 605 ⟶ 764:
Usage note: without the error messages being suppressed, the '''MKDIR''' command will issue an error message if the subdirectory (or its path) already exists.
<
trace off /*suppress possible warning msgs.*/
Line 611 ⟶ 770:
'MKDIR' dPath "2>nul" /*alias could be used: MD dPath */
/*stick a fork in it, we're done.*/</
=={{header|Ring}}==
<
System("mkdir C:\Ring\docs")
isdir("C:\Ring\docs")
Line 626 ⟶ 785:
return false
done
</syntaxhighlight>
=={{header|Ruby}}==
<
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.
=={{header|Run BASIC}}==
<
files #f, "c:\myDocs" ' check for directory
if #f hasanswer() then
Line 645 ⟶ 804:
else
shell$("mkdir c:\myDocs" ' if not exist make a directory
end if</
The following info about files / directory
FILE ACCESSOR methods
Line 665 ⟶ 824:
=={{header|Rust}}==
<
fn main() {
fs::create_dir_all("./path/to/dir").expect("An Error Occured!")
}</
=={{header|Scala}}==
<
Alternative (platform-independent) for the library function:
<
def mkdirs(path: List[String]) = // return true if path was created
Line 680 ⟶ 839:
mkdirs(List("/path", "to", "dir"))
</syntaxhighlight>
=={{header|Seed7}}==
Line 686 ⟶ 845:
defines the function doMkdirCmd, which is used below.
<
include "cli_cmds.s7i";
Line 692 ⟶ 851:
begin
doMkdirCmd(argv(PROGRAM), TRUE);
end func;</
The library cli_cmds.s7i defines also
Line 701 ⟶ 860:
The function doMkdir is used in the alternate solution below:
<
include "cli_cmds.s7i";
Line 710 ⟶ 869:
parameters := join(argv(PROGRAM), " ");
doMkdir(parameters);
end func;</
=={{header|Sidef}}==
<
=={{header|Tcl}}==
Tcl's built in <code>file mkdir</code> works exactly this way:
<
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 723 ⟶ 882:
{{works with|Bourne Again SHell}}
<
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Main()
Line 733 ⟶ 892:
End Sub
End Module</
=={{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}}==
This is for Unix as zkl doesn't have a built in mkdir method.
<
The system error code is returned (0 in this case).
<
{{out}}
<pre>
|