Create a file

From Rosetta Code
Jump to: navigation, search
Task
Create a file
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.

Contents

[edit] 4DOS Batch

echos > output.txt
mkdir docs
 
echos > \output.txt
mkdir \docs

[edit] Ada

Notes:

  • Use Streams_IO to write 0 bytes. File creation with Ada.Text_IO does not create 0 byte files (it inserts EOL/EOF).
  • The forward slash (/) notation works in Windows XP as well as Unix/Linux.
with Ada.Streams.Stream_IO, Ada.Directories;
use Ada.Streams.Stream_IO, Ada.Directories;
 
procedure File_Creation is
 
File_Handle : File_Type;
 
begin
 
Create (File_Handle, Out_File, "output.txt");
Close (File_Handle);
Create_Directory("docs");
Create (File_Handle, Out_File, "/output.txt");
Close (File_Handle);
Create_Directory("/docs");
 
end File_Creation;

[edit] Aikido

 
var sout = openout ("output.txt") // in current dir
sout.close()
 
var sout1 = openout ("/output.txt") // in root dir
sout1.close()
 
mkdir ("docs")
mkdir ("/docs")
 
 

[edit] Aime

# Make a directory using the -mkdir- program
void
mkdir(text p)
{
sshell ss;
 
b_cast(ss_path(ss), "mkdir");
 
l_append(ss_argv(ss), "mkdir");
l_append(ss_argv(ss), p);
 
ss_link(ss);
}
 
void
create_file(text p)
{
file f;
 
f_open(f, p, OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644);
}
 
void
create_pair(text prefix)
{
create_file(cat(prefix, "output.txt"));
mkdir(cat(prefix, "docs"));
}
 
integer
main(void)
{
create_pair("");
create_pair("/");
 
return 0;
}

[edit] ALGOL 68

Note: file names are Operating System dependent.

  • ALGOL 68G does not support pages, and "set" procedure only has 2 arguments.
  • ELLA ALGOL 68 also encounters problems with "set" page on linux.
Works with: ALGOL 68 version Standard - no extensions to language used

It may be best to to use an operating system provided library.

main:(
 
INT errno;
 
PROC touch = (STRING file name)INT:
BEGIN
FILE actual file;
INT errno := open(actual file, file name, stand out channel);
IF errno NE 0 THEN GO TO stop touch FI;
close(actual file); # detach the book and keep it #
errno
EXIT
stop touch:
errno
END;
 
errno := touch("input.txt");
errno := touch("/input.txt");
 
# ALGOL 68 has no concept of directories,
however a file can have multiple pages,
the pages are identified by page number only #

 
PROC mkpage = (STRING file name, INT page x)INT:
BEGIN
FILE actual file;
INT errno := open(actual file, file name, stand out channel);
IF errno NE 0 THEN GO TO stop mkpage FI;
set(actual file,page x,1,1); # skip to page x, line 1, character 1 #
close(actual file); # detach the new page and keep it #
errno
EXIT
stop mkpage:
errno
END;
 
errno := mkpage("input.txt",2);
)

[edit] APL

      'output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
'\output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
⎕mkdir 'Docs'
⎕mkdir '\Docs'

[edit] AppleScript

AppleScript itself has limited built-in File System access, but folders (directories) can be created by controlling the Mac OS Finder, and files can be created and accessed using the Standard Additions (osax) scripting addition included with AppleScript. Also, the Finder has no concept of the working directory (as it is a GUI). You can however target the frontmost Finder window that is open.

Create a zero-byte text file on the startup disk (root directory). Note: the close command is a memory allocation housekeeping command that should be performed once file access is complete.

close (open for access "output.txt")

Create a new folder (directory) on the startup disk (root directory).

tell application "Finder" to make new folder at startup disk with properties {name:"docs"}

Create a zero-byte text file in the frontmost (open) Finder window.

tell application "Finder" to set wd to target of window 1 as string
close (open for access wd & "output.txt")

Create a new folder (directory) in the frontmost (open) Finder window.

tell application "Finder" to make new folder at window 1 with properties {name:"docs"}

--Apl.way 21:20, 9 June 2010 (UTC)

[edit] AutoHotkey

FileAppend,,output.txt
FileCreateDir, docs
FileAppend,,c:\output.txt
FileCreateDir, c:\docs

[edit] AWK

There's no way to create a directory, except by calling an extern program (like mkdir) to do so.

BEGIN {
printf "" > "output.txt"
# try to create the file in the root (for *nix-like systems)
printf "" > "/output.txt"
}

[edit] BASIC

OPEN "output.txt" FOR OUTPUT AS 1
CLOSE
OPEN "\output.txt" FOR OUTPUT AS 1
CLOSE

[edit] Batch File

copy nul output.txt
copy nul \output.txt
md docs
md \docs

[edit] BBC BASIC

      CLOSE #OPENOUT("output.txt")
CLOSE #OPENOUT("\output.txt")
*MKDIR docs
*MKDIR \docs

[edit] Bracmat

put$(,"output.txt",NEW)

Or

fil$("output.txt",w)

In the latter case the file is still open, so unless the file is implicitly flushed and closed by ending the Bracmat program, you would want to close it explicitly:

fil$(,SET,-1)

To create a directory we are dependent on the underlying OS. In DOS:

sys$"mkdir docs"

And in the file system root:

sys$"mkdir \\docs"

[edit] C

ISO C (directory creation not supported):

#include <stdio.h>
 
int main() {
FILE *fh = fopen("output.txt", "w");
fclose(fh);
 
return 0;
}

POSIX:

Works with: POSIX
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
 
int main() { /* permissions are before umask */
int fd = open("output.txt", O_WRONLY|O_CREAT|O_TRUNC, 0640); /* rights 0640 for rw-r----- */
/* or equivalently:
int fd = creat("output.txt", 0640); */
/* rights 0640 for rw-r----- */
close(fd);
 
mkdir("docs", 0750); /* rights 0750 for rwxr-x--- */
 
return 0;
}

(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")

[edit] C++

Uses some Microsoft library:

#include <fstream>
#include <direct.h>
 
int main() {
std::fstream f( "output.txt", std::ios::out );
f.close();
f.open( "/output.txt", std::ios::out );
f.close();
 
_mkdir( "docs" );
_mkdir( "/docs" );
 
return 0;
}

[edit] C#

using System;
using System.IO;
 
class Program {
static void Main(string[] args) {
File.Create("output.txt");
File.Create(@"\output.txt");
 
Directory.CreateDirectory("docs");
Directory.CreateDirectory(@"\docs");
}
}

[edit] Clojure

(import '(java.io File))
(.createNewFile (new File "output.txt"))
(.mkdir (new File "docs"))
(.createNewFile (File. (str (File/separator) "output.txt")))
(.mkdir (File. (str (File/separator) "docs")))

[edit] Common Lisp

Lisp provides open and close commands for I/O with files
(let ((stream (open "output.txt" :direction :output)))
(close stream))

but it is more common to use with-open-file which has better exception handling.

(with-open-file (stream "output.txt" :direction :output)
;; use the stream here
)

As lisp is capable of being run on many different platforms and no assumptions should be made about the filesystem there are functions to construct paths in a platform independent manner

(let ((paths (list (make-pathname :directory '(:relative "docs"))
(make-pathname :directory '(:absolute "docs")))))
(mapcar #'ensure-directories-exist paths))

So creating a file called output.txt with an absolute path in the root directory becomes:

(with-open-file 
(stream
(make-pathname :directory '(:absolute "") :name "output.txt")
:direction :output))

On the other hand, if you may depend on the platform's pathname syntax then shorter notation may be used:

(mapcar #'ensure-directories-exist '(#p"docs/" #p"/docs/")))

[edit] D

For file creation, std.file.write function & std.stream.file class are used.
For dir creation, std.file.mkdir is used.

module fileio ;
import std.stdio ;
import std.path ;
import std.file ;
import std.stream ;
 
string[] genName(string name){
string cwd = curdir ~ sep ; // on current directory
string root = sep ; // on root
name = std.path.getBaseName(name) ;
return [cwd ~ name, root ~ name] ;
}
void Remove(string target){
if(exists(target)){
if (isfile(target))
std.file.remove(target);
else
std.file.rmdir(target) ;
}
}
void testCreate(string filename, string dirname){
// files:
foreach(fn ; genName(filename))
try{
writefln("file to be created : %s", fn) ;
std.file.write(fn, cast(void[])null) ;
writefln("\tsuccess by std.file.write") ; Remove(fn) ;
(new std.stream.File(fn, FileMode.OutNew)).close() ;
writefln("\tsuccess by std.stream") ; Remove(fn) ;
} catch(Exception e) {
writefln(e.msg) ;
}
// dirs:
foreach(dn ; genName(dirname))
try{
writefln("dir to be created : %s", dn) ;
std.file.mkdir(dn) ;
writefln("\tsuccess by std.file.mkdir") ; Remove(dn) ;
} catch(Exception e) {
writefln(e.msg) ;
}
}
void main(){
writefln("== test: File & Dir Creation ==") ;
testCreate("output.txt", "docs") ;
}



[edit] Delphi

These functions illustrate two methods for creating text files in Delphi: standard text file I/O and filestreams.

 
program createFile;
 
{$APPTYPE CONSOLE}
 
uses
Classes,
SysUtils;
 
const
filename = 'output.txt';
 
var
cwdPath,
fsPath: string;
 
 
// Create empty file in current working directory
function CreateEmptyFile1: Boolean;
var
f: textfile;
begin
// Make path to the file to be created
cwdPath := ExtractFilePath(ParamStr(0)) + '1_'+filename;
 
// Create file
AssignFile(f,cwdPath);
{$I-}
Rewrite(f);
{$I+}
Result := IOResult = 0;
CloseFile(f);
end;
 
// Create empty file in filesystem root
function CreateEmptyFile2: Boolean;
var
f: textfile;
begin
// Make path to the file to be created
fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '2_'+filename;
 
// Create file
AssignFile(f,fsPath);
{$I-}
Rewrite(f);
{$I+}
Result := IOResult = 0;
CloseFile(f);
end;
 
function CreateEmptyFile3: Boolean;
var
fs: TFileStream;
begin
// Make path to the file to be created
cwdPath := ExtractFilePath(ParamStr(0)) + '3_'+filename;
 
// Create file
fs := TFileStream.Create(cwdPath,fmCreate);
fs.Free;
Result := FileExists(cwdPath);
end;
 
function CreateEmptyFile4: Boolean;
var
fs: TFileStream;
begin
// Make path to the file to be created
fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '4_'+filename;
 
// Create file
fs := TFileStream.Create(fsPath,fmCreate);
fs.Free;
Result := FileExists(fsPath);
end;
 
begin
if CreateEmptyFile1 then
Writeln('File created at '+cwdPath)
else
Writeln('Error creating file at '+cwdPath);
 
if CreateEmptyFile2 then
Writeln('File created at '+fsPath)
else
Writeln('Error creating file at '+fsPath);
 
if CreateEmptyFile3 then
Writeln('File created at '+cwdPath)
else
Writeln('Error creating file at '+cwdPath);
 
if CreateEmptyFile4 then
Writeln('File created at '+fsPath)
else
Writeln('Error creating file at '+fsPath);
 
// Keep console window open
Readln;
end.
 
 
 

[edit] DCL

open/write output_file output.txt
open/write output_file [000000]output.txt
create/directory [.docs]
create/directory [000000.docs]

[edit] E

<file:output.txt>.setBytes([])
<file:docs>.mkdir(null)
<file:///output.txt>.setBytes([])
<file:///docs>.mkdir(null)

[edit] Erlang

"/" is documented as working on Windows.

 
-module(new_file).
-export([main/0]).
 
main() ->
ok = file:write_file( "output.txt", <<>> ),
ok = file:make_dir( "docs" ),
ok = file:write_file( filename:join(["/", "output.txt"]), <<>> ),
ok = file:make_dir( filename:join(["/", "docs"]) ).
 

[edit] Euphoria

integer fn
 
-- In the current working directory
system("mkdir docs",2)
fn = open("output.txt","w")
close(fn)
 
-- In the filesystem root
system("mkdir \\docs",2)
fn = open("\\output.txt","w")
close(fn)

[edit] F#

open System.IO
 
[<EntryPoint>]
let main argv =
let fileName = "output.txt"
let dirName = "docs"
for path in ["."; "/"] do
ignore (File.Create(Path.Combine(path, fileName)))
ignore (Directory.CreateDirectory(Path.Combine(path, dirName)))
0

[edit] Factor

USE: io.directories
 
"output.txt" "/output.txt" [ touch-file ] bi@
"docs" "/docs" [ make-directory ] bi@

[edit] Fancy

["/", "./"] each: |dir| {
# create '/docs', then './docs'
Directory create: (dir ++ "docs")
# create files /output.txt, then ./output.txt
File open: (dir ++ "output.txt") modes: ['write] with: |f| {
f writeln: "hello, world!"
}
}

[edit] Forth

There is no means to create directories in ANS Forth.

 s" output.txt" w/o create-file throw ( fileid) drop
s" /output.txt" w/o create-file throw ( fileid) drop

[edit] Fortran

Works with: Fortran version 90 and later

Don't know a way of creating directories in Fortran

OPEN (UNIT=5, FILE="output.txt", STATUS="NEW")   ! Current directory
CLOSE (UNIT=5)
OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") ! Root directory
CLOSE (UNIT=5)

[edit] friendly interactive shell

Translation of: UNIX Shell
touch {/,}output.txt    # create both /output.txt and output.txt
mkdir {/,}docs # create both /docs and docs

[edit] Go

package main
 
import (
"fmt"
"os"
)
 
func createFile(fn string) {
// create new; don't overwrite an existing file.
f, err := os.Create(fn)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("file", fn, "created!")
f.Close()
}
 
func createDir(dn string) {
err := os.Mkdir(dn, 0666)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("directory", dn, "created!")
}
 
func main() {
createFile("input.txt")
createFile("/input.txt")
createDir("docs")
createDir("/docs")
}

[edit] Groovy

new File("output.txt").createNewFile()
new File(File.separator + "output.txt").createNewFile()
new File("docs").mkdir()
new File(File.separator + "docs").mkdir()

[edit] Haskell

import System.Directory
 
createFile name = writeFile name ""
 
main = do
createFile "output.txt"
createDirectory "docs"
createFile "/output.txt"
createDirectory "/docs"

[edit] HicEst

SYSTEM(DIR="\docs")              ! create argument if not existent, make it current
OPEN(FILE="output.txt", "NEW") ! in current directory
 
SYSTEM(DIR="C:\docs") ! create C:\docs if not existent, make it current
OPEN(FILE="output.txt", "NEW") ! in C:\docs

[edit] Icon and Unicon

Icon does not support 'mkdir' - otherwise the Unicon code below will work. A work around would be to use 'system' to invoke command line to create a directory.

every dir := !["./","/"] do {
close(open(f := dir || "input.txt","w")) |stop("failure for open ",f)
mkdir(f := dir || "docs") |stop("failure for mkdir ",f)
}

Note: Icon and Unicon accept both / and \ for directory separators.

[edit] J

The conjunction !: with a scalar 1 to the left (1!:) provides the underlying cross-platform support for working with files.

'' 1!:2 <'/output.txt'   NB. write an empty file
1!:5 <'/docs' NB. create a directory

However a number of libraries provide a more convenient/conventional interface to that underlying functionality.

require 'files'
NB. create two empty files named /output.txt and output.txt
'' fwrite '/output.txt' ; 'output.txt'
 
require 'general/dirutils' NB. addon package
NB. create two directories: /docs and docs:
dircreate '/docs' ; 'docs'

Finally note that writing a file in J creates that file. In typical use, files are referred to by name, and the entire contents of the file are written. (Appends and partial writes are also supported but they are more complicated than the typical case.)

[edit] See Also

[edit] Java

import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}

[edit] JCL

 
// EXEC PGM=IEFBR14
//* CREATE EMPTY FILE NAMED "OUTPUT.TXT" (file names upper case only)
//ANYNAME DD UNIT=SYSDA,SPACE=(0,0),DSN=OUTPUT.TXT,DISP=(,CATLG)
//* CREATE DIRECTORY (PARTITIONED DATA SET) NAMED "DOCS"
//ANYNAME DD UNIT=SYSDA,SPACE=(TRK,(1,1)),DSN=DOCS,DISP=(,CATLG)
 

[edit] K

Directory creation is OS-dependent

Works with: Kona
   "output.txt" 1: ""
"/output.txt" 1: ""
\ mkdir docs
\ mkdir /docs

[edit] LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
LabVIEW Create a file.png


[edit] Lasso

// create file
local(f) = file
handle => { #f->close }
#f->openWriteOnly('output.txt')
 
// make directory, just like a file
local(d = dir('docs'))
#d->create
 
// create file in root file system (requires permissions at user OS level)
local(f) = file
handle => { #f->close }
#f->openWriteOnly('//output.txt')
 
// create directory in root file system (requires permissions at user OS level)
local(d = dir('//docs'))
#d->create

[edit] Liberty BASIC

Filenames without drive and directory info. refer to the same directory as the LB program is running from.
Full pathnames including drive name and directory can be used- back-slash separated.

 
nomainwin
 
open "output.txt" for output as #f
close #f
 
result = mkdir( "F:\RC")
if result <>0 then notice "Directory not created!": end
 
open "F:\RC\output.txt" for output as #f
close #f
 
end
 

[edit] LFE

 
(: file write_file '"output.txt" '"Some data")
(: file make_dir '"docs")
(: file write_file '"/output.txt" '"Some data")
(: file make_dir '"/docs")
 

[edit] Lua

Works with: Lua version 5.1

[edit] Create File

io.open("output.txt", "w"):close()
io.open("\\output.txt", "w"):close()

[edit] Create Directory

This solution sends the command to the OS shell.

os.execute("mkdir docs")
os.execute("mkdir \\docs")

A more portable solution requires a library such as LuaFileSystem.

require "lfs"
lfs.mkdir("docs")
lfs.mkdir("/docs")

[edit] Mathematica

 
SetDirectory@NotebookDirectory[];
t = OpenWrite["output.txt"]
Close[t]
s = OpenWrite[First@FileNameSplit[$InstallationDirectory] <> "\\output.txt"]
Close[s]
 
(*In root directory*)
CreateDirectory["\\docs"]
(*In current operating directory*)
CreateDirectory[Directory[]<>"\\docs"]
(* "<>" is shorthand for "StringJoin[left,right]" *)
 
 

[edit] MATLAB / Octave

	fid = fopen('output.txt','w'); fclose(fid);
fid = fopen('/output.txt','w'); fclose(fid);
mkdir('docs');
mkdir('/docs');

[edit] Maxima

f: openw("/output.txt");
close(f);
 
f: openw("output.txt");
close(f);
 
/* Maxima has no function to create directories, but one can use the underlying Lisp system */
 
:lisp (mapcar #'ensure-directories-exist '("docs/" "/docs/"))


[edit] MAXScript

-- Here
f = createFile "output.txt"
close f
makeDir (sysInfo.currentDir + "\docs")
-- System root
f = createFile "\output.txt"
close f
makeDir ("c:\docs")

[edit] Mercury

:- module create_file.
:- interface.
 
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
 
:- import_module dir.
 
main(!IO) :-
create_file("output.txt", !IO),
create_file("/output.txt", !IO),
create_dir("docs", !IO),
create_dir("/docs", !IO).
 
:- pred create_file(string::in, io::di, io::uo) is det.
 
create_file(FileName, !IO) :-
io.open_output(FileName, Result, !IO),
(
Result = ok(File),
io.close_output(File, !IO)
 ;
Result = error(Error),
print_io_error(Error, !IO)
).
 
:- pred create_dir(string::in, io::di, io::uo) is det.
 
create_dir(DirName, !IO) :-
dir.make_single_directory(DirName, Result, !IO),
(
Result = ok
 ;
Result = error(Error),
print_io_error(Error, !IO)
).
 
:- pred print_io_error(io.error::in, io::di, io::uo) is det.
 
print_io_error(Error, !IO) :-
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.nl(Stderr, !IO),
io.set_exit_status(1, !IO).

[edit] Mirah

import java.io.File
 
File.new('output.txt').createNewFile()
File.new('docs').mkdir()
File.new("docs#{File.separator}output.txt").createNewFile()
 

[edit] Modula-3

MODULE FileCreation EXPORTS Main;
 
IMPORT FS, File, OSError, IO, Stdio;
 
VAR file: File.T;
 
BEGIN
TRY
file := FS.OpenFile("output.txt");
file.close();
FS.CreateDirectory("docs");
file := FS.OpenFile("/output.txt");
file.close();
FS.CreateDirectory("/docs");
EXCEPT
| OSError.E => IO.Put("Error creating file or directory.\n", Stdio.stderr);
END;
END FileCreation.

[edit] Nemerle

using System;
using System.IO;
 
module CreateFile
{
Main() : void
{
unless (File.Exists("output.txt")) File.Create("output.txt"); // here
// returns a FileStream object which we're ignoring
try {
unless (File.Exists(@"\output.txt")) File.Create(@"\output.txt"); // root
}
catch {
|e is UnauthorizedAccessException => Console.WriteLine(
"Cannot create file in root directory without Administrator priveleges.")
}
 
unless (Directory.Exists("docs")) Directory.CreateDirectory("docs");
// returns a DirectoryInfo object which we're ignoring
unless (Directory.Exists(@"\docs")) Directory.CreateDirectory(@"\docs");
// no Exception for directory creation
}
}

[edit] NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary
 
fName = ''; fName[0] = 2; fName[1] = '.' || File.separator || 'output.txt'; fName[2] = File.separator || 'output.txt'
dName = ''; dName[0] = 2; dName[1] = '.' || File.separator || 'docs'; dName[2] = File.separator || 'docs'
 
do
loop i_ = 1 to fName[0]
say fName[i_]
fc = File(fName[i_]).createNewFile()
if fc then say 'File' fName[i_] 'created successfully.'
else say 'File' fName[i_] 'aleady exists.'
end i_
 
loop i_ = 1 to dName[0]
say dName[i_]
dc = File(dName[i_]).mkdir()
if dc then say 'Directory' dName[i_] 'created successfully.'
else say 'Directory' dName[i_] 'aleady exists.'
end i_
catch iox = IOException
iox.printStackTrace
end
 
return
 

[edit] Objective-C

NSFileManager *fm = [NSFileManager defaultManager];
 
[fm createFileAtPath:@"output.txt" contents:[NSData data] attributes:nil];
// Pre-OS X 10.5
[fm createDirectoryAtPath:@"docs" attributes:nil];
// OS X 10.5+
[fm createDirectoryAtPath:@"docs" withIntermediateDirectories:NO attributes:nil error:NULL];

[edit] Objeck

 
use IO;
 
bundle Default {
class FileExample {
function : Main(args : String[]) ~ Nil {
file := FileWriter->New("output.txt");
file->Close();
 
file := FileWriter->New("/output.txt");
file->Close();
 
Directory->Create("docs");
Directory->Create("/docs");
}
}
}
 

[edit] OCaml

# let oc = open_out "output.txt" in
close_out oc;;
- : unit = ()
 
# Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *)
- : unit = ()

(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")

[edit] Oz

for Dir in ["/" "./"] do
File = {New Open.file init(name:Dir#"output.txt" flags:[create])}
in
{File close}
{OS.mkDir Dir#"docs" ['S_IRUSR' 'S_IWUSR' 'S_IXUSR' 'S_IXGRP']}
end


[edit] Pascal

The Pascal & Delphi Standard Libraries support all of this functionality.

 
program in out;
 
var
 
f : textfile;
 
begin
 
assignFile(f,'/output.txt');
rewrite(f);
close(f);
makedir('/docs');
assignFile(f,'/docs/output.txt');
rewrite(f);
close(f);
 
end;
 


[edit] Perl

use File::Spec::Functions qw(catfile rootdir);
{ # here
open my $fh, '>', 'output.txt';
mkdir 'docs';
};
{ # root dir
open my $fh, '>', catfile rootdir, 'output.txt';
mkdir catfile rootdir, 'docs';
};

Without Perl Modules

Current directory

perl -e 'qx(touch output.txt)'
perl -e 'mkdir docs'

Root directory

perl -e 'qx(touch /output.txt)'
perl -e 'mkdir "/docs"'

For comparison with Perl 6

for my $prefix (qw( ./ / )) {
mkdir "${prefix}docs";
open my $FH, '>', "${prefix}docs/output.txt";
}

Cleanup

unlink $_ for qw(/docs/output.txt ./docs/output.txt);
rmdir $_ for qw(/docs ./docs);

[edit] Perl 6

 
for '.', '' -> $prefix {
mkdir "$prefix/docs";
open "$prefix/output.txt", :w;
}
 

[edit] PHP

<?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?>

[edit] PicoLisp

(out "output.txt")                     # Empty output
(call 'mkdir "docs") # Call external
(out "/output.txt")
(call 'mkdir "/docs")

[edit] Pike

import Stdio;
 
int main(){
write_file("input.txt","",0100);
write_file("/input.txt","",0100);
}

[edit] PL/I

 
open file (output) title ('/OUTPUT.TXT,type(text),recsize(100)' );
close file (output);
 

[edit] PowerShell

New-Item output.txt -ItemType File
New-Item \output.txt -ItemType File
New-Item docs -ItemType Directory
New-Item \docs -ItemType Directory

[edit] ProDOS

makedirectory docs
changedirectory docs
makenewfile output.txt

[edit] PureBasic

CreateFile(0,"output.txt"):CloseFile(0)
CreateDirectory("docs")
CreateFile(0,"/output.txt"):CloseFile(0)
CreateDirectory("/docs")

[edit] Python

import os
for directory in ['/', './']:
open(directory + 'output.txt', 'w').close() # create /output.txt, then ./output.txt
os.mkdir(directory + 'docs') # create directory /docs, then ./docs
Works with: Python version 2.5

Exception-safe way to create file:

from __future__ import with_statement
import os
def create(directory):
with open(os.path.join(directory, "output.txt"), "w"):
pass
os.mkdir(os.path.join(directory, "docs"))
 
create(".") # current directory
create("/") # root directory

[edit] R

f <- file("output.txt", "w")
close(f)
 
# it may fails and the exact syntax to achieve the root
# changes according to the operating system
f <- file("/output.txt", "w")
close(f)
 
success <- dir.create("docs")
success <- dir.create("/docs")

[edit] Racket

#lang racket
 
(display-to-file "" "output.txt")
(make-directory "docs")
(display-to-file "" "/output.txt")
(make-directory "/docs")

[edit] Raven

"" as str
str 'output.txt' write
str '/output.txt' write
'docs' mkdir
'/docs' mkdir

[edit] REBOL

; Creating in current directory:
 
write %output.txt ""
make-dir %docs/
 
; Creating in root directory:
 
write %/output.txt ""
make-dir %/docs/
 

[edit] Retro

There are no facilities in Retro to create directories.

with files'
"output.txt" :w open close drop
"/output.txt" :w open close drop

[edit] REXX

This REXX version works under Microsoft Windows (any version).

/*REXX pgm creates a new empty file and directory; in curr dir and root.*/
do 2 /*perform three statements twice.*/
'COPY NUL output.txt' /*copy a "null" (empty) file. */
'MKDIR DOCS' /*make a directory (aka: folder).*/
'CD \' /*change currect dir to the root.*/
end /*2*/ /*now, go and perform them again.*/
/*stick a fork in it, we're done.*/

[edit] Ruby

['/', './'].each{|dir|
Dir.mkdir(dir + 'docs') # create '/docs', then './docs'
File.open(dir + 'output.txt', 'w') {} # create empty file /output.txt, then ./output.txt
}

[edit] Run BASIC

open "output.txt" for output as #f
close #f
 
dirOk = mkdir( "f:\doc")
if not(dirOk) then print "Directory not created!": end
 
open "f:\doc\output.txt" for output as #f
close #f

[edit] Scheme

(open-output-file "output.txt")
(open-output-file "/output.txt")

Results:

> file output.txt
output.txt: empty
> file /output.txt
/output.txt: empty

I am not aware of any standard way of creating directories in Scheme.

[edit] Seed7

Seed7 uses a standard path representation to make paths operating system independent. In the standard path representation a / is used as path delimiter and drive letters like C: must be written as /c instead. Creating files and directories in a file system root may need privileges, so the program may fail, when it is started by a normal user.

$ include "seed7_05.s7i";
include "osfiles.s7i";
 
const proc: main is func
local
var file: aFile is STD_NULL;
begin
aFile := open("output.txt", "w");
close(aFile);
mkdir("docs");
aFile := open("/output.txt", "w");
close(aFile);
mkdir("/docs");
end func;

Under Windows each filesystem has its own root. Therefore you need to replace "/output.txt" and "/docs" with "/c/output.txt" and "/c/docs".

[edit] Slate

File creation locally:

(File newNamed: 'output.txt') touch.
(Directory current / 'output.txt') touch.

File creation at root:

(File newNamed: '/output.txt') touch.
(Directory root / 'output.txt') touch.

[edit] Smalltalk

Squeak has no notion of 'current directory' because it isn't tied to the shell that created it.

(FileDirectory on: 'c:\') newFileNamed: 'output.txt'; createDirectory: 'docs'.

In GNU Smalltalk you can do instead:

ws := (File name: 'output.txt') writeStream.
ws close.
Directory create: 'docs'.
 
ws := (File name: '/output.txt') writeStream.
ws close.
Directory create: '/docs'.

[edit] SNOBOL4

Works with: Macro Spitbol
Works with: CSnobol
        output(.file,1,'output.txt');  endfile(1)  ;* Macro Spitbol
* output(.file,1,,'output.txt'); endfile(1)  ;* CSnobol
host(1,'mkdir docs')
 
output(.file,1,'/output.txt'); endfile(1) ;* Macro Spitbol
* output(.file,1,,'/output.txt'); endfile(1) ;* CSnobol
host(1,'mkdir /docs')
end

[edit] Standard ML

let val out = TextIO.openOut "output.txt" in
TextIO.closeOut out
end;
 
OS.FileSys.mkDir "docs";

(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")

[edit] Tcl

Assuming that we're supposed to create two files and two directories (one each here and one each in the file system root) and further assuming that the code is supposed to be portable, i.e. work on win, linux, MacOS (the task is really not clear):

close [open output.txt w] 
close [open [file nativename /output.txt] w]
 
file mkdir docs
file mkdir [file nativename /docs]

[edit] Toka

needs shell
" output.txt" "W" file.open file.close
" /output.txt" "W" file.open file.close
 
( Create the directories with permissions set to 777)
" docs" &777 mkdir
" /docs" &777 mkdir

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
- create file
ERROR/STOP CREATE ("output.txt",FDF-o,-std-)
- create directory
ERROR/STOP CREATE ("docs",project,-std-)
 

[edit] Vedit macro language

When closing a file, Vedit saves it only if it has been modified. Therefore, in order to create an empty file, we first insert a character in the file and then delete it.

// In current directory
File_Open("input.txt") Ins_Char(' ') Del_Char(-1) Buf_Close()
File_Mkdir("docs")
 
// In the root directory
File_Open("/input.txt") Ins_Char(' ') Del_Char(-1) Buf_Close()
File_Mkdir("/docs")

[edit] Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+
 'Current Directory
IO.Directory.CreateDirectory("docs")
IO.File.Create("output.txt").Close()
 
'Root
IO.Directory.CreateDirectory("\docs")
IO.File.Create("\output.txt").Close()
 
'Root, platform independent
IO.Directory.CreateDirectory(IO.Path.DirectorySeparatorChar & "docs")
IO.File.Create(IO.Path.DirectorySeparatorChar & "output.txt").Close()

[edit] UNIX Shell

Works with: Bourne Shell
touch output.txt /output.txt   # create both output.txt and /output.txt
mkdir /docs
mkdir docs # create both /docs and docs
Works with: bash
touch {/,}output.txt    # create both /output.txt and output.txt
mkdir {/,}docs # create both /docs and docs

[edit] X86 Assembly

Works with: NASM version Linux
 
; syscall numbers for readability. :]
 
%define sys_mkdir 39
%define sys_creat 8
 
section .data
fName db 'doc/output.txt',0
rfName db '/output.txt',0
dName db 'doc',0
 
err_msg db "Something went wrong! :[",0xa
err_len equ $-err_msg
 
section .text
global _start
 
_start:
 
nop
mov ebx, dName ; Directory name
mov eax, sys_mkdir ; Specify sys_mkdir call
mov ecx, 0750o ; permission (rwxr-x---)
int 0x80 ; Make kernel call
 
mov ebx, fName ; File name
mov eax, sys_creat ; Specify sys_creat call
mov ecx, 0640o ; permission (rw-r-----)
int 0x80 ; Make kernel call
test eax, eax ; eax AND eax
js _ragequit ; If EAX is less than zero
; THEN Display Message Error
 
mov ebx, rfName ; File name Root
mov eax, sys_creat ; Specify sys_creat call
mov ecx, 0777o ; permission (rwxrwxrwx)
int 0x80 ; Make kernel call
cmp eax, 0
jle _exit ; IF EAX is less or equal than zero
; THEN jump to EXIT
; ELSE Display Message Error
 
_ragequit:
mov edx, err_len ; Pass offset of the message error
mov ecx, err_msg ; Pass the length of the message error
mov eax, 4 ; Specify sys_write call
mov ebx, 2 ; Specify File Descriptor 2: Error Output
int 0x80 ; Make kernel call
 
_exit:
push 0x1
mov eax, 1 ; Code for Exit Syscall
push eax
int 0x80 ; Make kernel call
ret
 

[edit] ZX Spectrum Basic

The ZX Spectrum saves to a tape recorder and does not have subdirectories. Here we create an empty file named OUTPUT of zero bytes. We can use any start address, because the file is empty. Here we write zero bytes from address 16384:

SAVE "OUTPUT" CODE 16384,0
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox