Jump to content

Create a file

From Rosetta Code
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.

11l

Translation of: Python
L(directory) [‘/’, ‘./’]
   File(directory‘output.txt’, ‘w’) // create /output.txt, then ./output.txt
   fs:create_dir(directory‘docs’)   // create directory /docs, then ./docs

4DOS Batch

echos > output.txt
mkdir docs

echos > \output.txt
mkdir \docs

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program createDirFic64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ MKDIRAT, 0x22     // Linux Syscall  create directory
.equ CHGDIR,  0x31     // Linux Syscall  change directory

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessCreateDirOk:   .asciz "Create directory Ok.\n"
szMessErrCreateDir:  .asciz "Unable create directory. \n"
szMessErrChangeDir:  .asciz "Unable change directory. \n"
szMessCreateFileOk:  .asciz "Create file Ok.\n"
szMessErrCreateFile: .asciz "Unable create file. \n"
szMessErrCloseFile:  .asciz "Unable close file. \n"
 
szNameDir:           .asciz "Dix1"
szNameFile:          .asciz "file1.txt"
 
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main:                           // entry of program 
                                // create directory
    mov x0,AT_FDCWD
    ldr x1,qAdrszNameDir        // directory name
    mov x2,0775                 // mode (in octal zero is important !!)
    mov x8,MKDIRAT              // code call system create directory 
    svc 0                       // call systeme 
    cbnz x0,99f                 // error ?
 
                                // display  message ok directory
    ldr x0,qAdrszMessCreateDirOk
    bl affichageMess
                                // change directory
    ldr x0,qAdrszNameDir        // directory name
    mov x8, #CHGDIR             // code call system change directory 
    svc #0                      // call systeme 
    cbnz x0,98f                 // error ?
                                // create file
    mov x0,AT_FDCWD             // current directory
    ldr x1,qAdrszNameFile       // directory name
    mov x2,O_CREAT|O_WRONLY     //  flags
    mov x3,0644                 // this zone is Octal number (0 before)
    mov x8,OPEN                 // code call system open file
    svc #0                      // call systeme 
    cmp x0,#0                   // error ?
    ble 97f
    mov x19,x0                  // save File Descriptor 
                                // display  message ok file
    ldr x0,qAdrszMessCreateFileOk
    bl affichageMess
 
                                // close file
    mov x0,x19                  // Fd 
    mov x8,CLOSE                // close file
    svc 0 
    cbnz x0,96f                 // error ?
    mov x0,0                    // return code Ok
    b 100f                      // end Ok
96:                             // display error message close file 
    ldr x0,qAdrszMessErrCloseFile
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
97:                             // display error message create file 
    ldr x0,qAdrszMessErrCreateFile
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
98:                             // display error message change directory 
    ldr x0,qAdrszMessErrChangeDir
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
99:                             // display error message create directory 
    ldr x0,qAdrszMessErrCreateDir
    bl affichageMess
    mov x0,1                    // return code error
    b 100f
100:                            // standard end of the program 
    mov x8,EXIT                 // request to exit program
    svc 0                       // perform the system call
qAdrszMessCreateDirOk:     .quad szMessCreateDirOk
qAdrszMessErrCreateDir:    .quad szMessErrCreateDir
qAdrszMessErrChangeDir:    .quad szMessErrChangeDir
qAdrszMessCreateFileOk:    .quad szMessCreateFileOk
qAdrszNameFile:            .quad szNameFile
qAdrszMessErrCreateFile:   .quad szMessErrCreateFile
qAdrszMessErrCloseFile:    .quad szMessErrCloseFile
qAdrszNameDir:             .quad szNameDir
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

Action!

The attached result has been obtained under DOS 2.5.

PROC Dir(CHAR ARRAY filter)
  CHAR ARRAY line(255)
  BYTE dev=[1]

  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    PrintE(line)
    IF line(0)=0 THEN
      EXIT
    FI
  OD
  Close(dev)
RETURN

PROC CreateFile(CHAR ARRAY fname)
  BYTE dev=[1]

  Close(dev)
  Open(dev,fname,8)
  Close(dev)
RETURN

PROC Main()
  CHAR ARRAY filter="D:*.*", fname="D:OUTPUT.TXT"

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)

  PrintF("Create file ""%S""%E%E",fname)
  CreateFile(fname)

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)
RETURN
Output:

Screenshot from Atari 8-bit computer

Dir "D:*.*"
  DOS     SYS 037
  DUP     SYS 042
628 FREE SECTORS

Create file "D:OUTPUT.TXT"

Dir "D:*.*"
  DOS     SYS 037
  DUP     SYS 042
  OUTPUT  TXT 001
627 FREE SECTORS

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;

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")

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;
}

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);
)

APL

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

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)

Observations on 28th February 2020:

  1. The command for closing a file access previously opened with open for access is close access, not close.
  2. While specifying just a file name did at one time cause the file to be created at the root level of the startup disk, this is now prevented by macOS's security measures:
    1. The system actively discourages the creation of files in that location.
    2. It's more likely to cooperate with file commands having AppleScript or application "specifiers" as parameters than it is when the parameters are merely text.
  3. In macOS, the "current working directory" is effectively the root level of the startup disk anyway, except in the Terminal application when "cd" is used or during a shell script containing "cd" which is being executed using AppleScript's do shell script command.
  4. In view of points 2.2 and 3 above, this task is ideally one that should not be casually performed on Mac computers.

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program createDirFic.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall   exit Program
.equ WRITE,  4     @ Linux syscall  write FILE
.equ MKDIR, 0x27  @ Linux Syscal  create directory
.equ CHGDIR, 0xC  @ Linux Syscal  change directory
.equ CREATE, 0x8 @ Linux Syscal  create file
.equ CLOSE,   0x6  @ Linux Syscal  close file
/* Initialized data */
.data
szMessCreateDirOk: .asciz "Create directory Ok.\n"
szMessErrCreateDir: .asciz "Unable create directory. \n"
szMessErrChangeDir: .asciz "Unable change directory. \n"
szMessCreateFileOk: .asciz "Create file Ok.\n"
szMessErrCreateFile: .asciz "Unable create file. \n"
szMessErrCloseFile: .asciz "Unable close file. \n"

szNameDir: .asciz "Dir1"
szNameFile:  .asciz "file1.txt"


/* UnInitialized data */
.bss 

/*  code section */
.text
.global main 
main:                @ entry of program 
    push {fp,lr}        @ saves registers 
	@ create directory
    ldr r0,iAdrszNameDir   @ directory name
    mov r1,#0775                 @ mode (in octal zero is important !!)
    mov r7, #MKDIR             @ code call system create directory 
    swi #0                      @ call systeme 
    cmp r0,#0             @ error ?
    bne 99f

   @ display  message ok directory
    ldr r0,iAdrszMessCreateDirOk
    bl affichageMess
    @ change directory
    ldr r0,iAdrszNameDir   @ directory name
    mov r7, #CHGDIR             @ code call system change directory 
    swi #0                      @ call systeme 
    cmp r0,#0     @ error ?
    bne 98f
    @ create file
    ldr r0,iAdrszNameFile   @ directory name
    mov r1,#0755                 @ mode (in octal zero is important !!)
    mov r2,#0
    mov r7,#CREATE             @ code call system create file
    swi #0                      @ call systeme 
    cmp r0,#0             @ error ?
    ble 97f
    mov r8,r0     @ save File Descriptor 
    @ display  message ok file
    ldr r0,iAdrszMessCreateFileOk
    bl affichageMess

    @ close file
    mov r0,r8       @ Fd 
    mov r7, #CLOSE @ close file
    swi 0 
    cmp r0,#0
    bne 96f
    @ end Ok
    b 100f
96:
    @ display error message close file 
    ldr r0,iAdrszMessErrCloseFile
    bl affichageMess
    b 100f
97:
    @ display error message create file 
    ldr r0,iAdrszMessErrCreateFile
    bl affichageMess
    b 100f
98:
    @ display error message change directory 
    ldr r0,iAdrszMessErrChangeDir
    bl affichageMess
    b 100f
99: 
    @ display error message create directory 
    ldr r0,iAdrszMessErrCreateDir
    bl affichageMess
    b 100f
100:   @ standard end of the program 
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszMessCreateDirOk:		.int szMessCreateDirOk
iAdrszMessErrCreateDir:	.int szMessErrCreateDir
iAdrszMessErrChangeDir:	.int szMessErrChangeDir
iAdrszMessCreateFileOk:	.int szMessCreateFileOk
iAdrszNameFile:				.int szNameFile
iAdrszMessErrCreateFile:	.int szMessErrCreateFile
iAdrszMessErrCloseFile:	.int szMessErrCloseFile

iAdrszNameDir:				.int szNameDir
/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */ 
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */ 
    bx lr	        			/* return  */

Arturo

output: "output.txt"
docs:   "docs"

write output ""
write.directory docs ø

write join.path ["/" output] ""
write.directory join.path ["/" docs] ø

AutoHotkey

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

AWK

BEGIN {
  printf "" > "output.txt"
  close("output.txt")
  printf "" > "/output.txt"
  close("/output.txt")
  system("mkdir docs")
  system("mkdir /docs")
}

Axe

Since the TI-OS does not have a true filesystem, this task is emulated using an application variable instead of a file.

GetCalc("appvOUTPUT",0)

BASIC

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

Applesoft BASIC

There are disk volumes, but no folders in DOS 3.3.

 0 D$ =  CHR$ (4): PRINT D$"OPEN OUTPUT.TXT": PRINT D$"CLOSE"

BaCon

' Create file and dir
TRAP LOCAL

OPEN "output.txt" FOR WRITING AS afile
CLOSE FILE afile

CATCH GOTO report
OPEN "/output.txt" FOR WRITING AS afile
CLOSE FILE afile

LABEL trydir
MAKEDIR "docs"

CATCH GOTO report2
MAKEDIR "/docs"
END

LABEL report
    PRINT ERR$(ERROR)
    GOTO trydir

LABEL report2
    PRINT ERR$(ERROR)
Output:
prompt$ ./creates
Error opening file: Permission denied
Unable to create directory: Permission denied
prompt$ ls -gocart
...
-rw-rw-r-- 1     324 May  2 23:53 creates.bac
-rwxrwxr-x 1   27184 May  2 23:53 creates
-rw-rw-r-- 1       0 May  2 23:53 output.txt
drwxr-xr-x 2    4096 May  2 23:53 docs
drwxrwxr-x 7   12288 May  2 23:53 .

Commodore BASIC

On most Commodore 8-bit systems, the most commonly used storage devices were floppy disk drives and cassette tape drives, however these file systems are typically flat (linear) and do not feature any kind of file hierarchy. It is possible that other third-party storage devices (hard drives, etc.) may support such hierarchies, however, the commands to create, delete, and/or navigate in and out of various directories would be unique and specialized to those devices.

The example below illustrates the syntax for the open statement which will create the file, however, something must be written to the file or else nothing will actually be created on the disk. In this case we will simply write a single null byte.

Even still, the empty file will still cause Commodore DOS to allocate 1 data block to the file, as reported in a directory listing.

10 rem create a file
20 open 10,8,10,"0:output.txt,seq,write"
30 print#10,chr$(0)
40 close 10
50 rem check device status for error
60 open 15,8,15:input#15,a,b$,c,d:print a;b$;c;d:close 15
RUN
 0 OK 0  0

READY.
LOAD "$",8

SEARCHING FOR $
LOADING
READY.
LIST

0 "ROSETTA CODE    " RC 2A
1    "OUTPUT.TXT"       SEQ  
663 BLOCKS FREE.             
READY.

SmallBASIC

Linux:

open "output.txt" for output as #1
close #1
open "/output.txt" for output as #1
close #1
 
mkdir( "docs")
mkdir( "/docs")

Windows:

open "output.txt" for output as #1
close #1
open "C:\\output.txt" for output as #1
close #1
 
mkdir( "docs")
mkdir( "C:\\docs")


Batch File

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

BBC BASIC

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

Blue

Linux/x86-64. If you really want to create a file and dir in the root, prefix the paths with a slash.

global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;

: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;

: open ( pathname:edi flags:esi mode:edx -- fd:eax ) 2 syscall unwrap ;
: close ( fd:edi -- ) 3 syscall ordie ;

: mkdir ( pathname:edi mode:esi -- ) 83 syscall ordie ;

00001 const for-writing
00100 const create
01000 const truncate

: create-file ( pathname -- ) 
	create for-writing or truncate or
	0640 open close ;

: make-directory ( pathname -- ) 0750 mkdir ;

: create-output-file ( -- ) s" output.txt" drop create-file ;
: make-docs-directory ( -- ) s" docs" drop make-directory ;

: _start ( -- noret ) 
	create-output-file 
	make-docs-directory 
	bye 
;

BQN

May require elevated privileges to run correctly. Paths are relative to the script's path by default, but can be resolved relative to the shell's working directory with •wdpath •file.At path.

"output.txt" •file.Chars ""
"/output.txt" •file.Chars ""
•file.CreateDir "docs"
•file.CreateDir "/docs"

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"

C

ISO 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")

Windows API

First, a solution with the C runtime functions _creat and _mkdir.

#include <direct.h>
#include <io.h>
#include <sys/stat.h>

int main(void) {
    int f;
    
    f = _creat("output.txt", _S_IWRITE);
    if (f == -1) {
        perror("Unable to create file");
    } else {
        _close(f);
    }
    
    if (_mkdir("docs") == -1) {
        perror("Unable to create directory");
    }
    
    f = _creat("\\output.txt", _S_IWRITE);
    if (f == -1) {
        perror("Unable to create file");
    } else {
        _close(f);
    }
    
    if (_mkdir("\\docs") == -1) {
        perror("Unable to create directory");
    }

    return 0;
}

Another solution with the kernel32 API functions CreateFile and CreateDirectory.

#include <windows.h>
#include <stdio.h>

int main(void) {
    HANDLE hFile;
    
    hFile = CreateFile("output.txt", GENERIC_WRITE, 0, NULL,
                       CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("Unable to create file\n");
    } else {
        CloseHandle(hFile);
    }
    
    if (CreateDirectory("docs", NULL) == 0) {
        printf("Unable to create directory\n");
    }

    hFile = CreateFile("\\output.txt", GENERIC_WRITE, 0, NULL,
                       CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("Unable to create file\n");
    } else {
        CloseHandle(hFile);
    }

    if (CreateDirectory("\\docs", NULL) == 0) {
        printf("Unable to create directory\n");
    }

    return 0;
}

OS/2

Using the OS/2 API functions DosOpen and DosMkDir.

#include <os2.h>

int main(void) {
    ULONG Result, ActionTaken, hFile;
    
    Result = DosOpen("output.txt", &hFile, &ActionTaken, 0L,
                     FILE_NORMAL,
                     OPEN_ACTION_REPLACE_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
                     OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE,
                     NULL);
    if (Result != 0) {
        printf("Unable to create file\n");
    } else {
        DosClose(hFile);
    }
    
    Result = DosMkDir("docs", NULL);
    if (Result != 0) {
        printf("Unable to create directory\n");
    }

    Result = DosOpen("\\output.txt", &hFile, &ActionTaken, 0L,
                     FILE_NORMAL,
                     OPEN_ACTION_REPLACE_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
                     OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE,
                     NULL);
    if (Result != 0) {
        printf("Unable to create file\n");
    } else {
        DosClose(hFile);
    }
    
    Result = DosMkDir("\\docs", NULL);
    if (Result != 0) {
        printf("Unable to create directory\n");
    }

    return 0;
}

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");
    }
}

C++

Uses some Microsoft library:

#include <direct.h>
#include <fstream>

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;
}

A cross-platform solution using C++17

#include <filesystem>
#include <fstream>

namespace fs = std::filesystem;

int main() {
    std::fstream f("output.txt", std::ios::out);
    f.close();
    f.open("/output.txt", std::ios::out);
    f.close();

    fs::create_directory("docs");
    fs::create_directory("/docs");
}

ChucK

This creates a file in root:

FileIO text;
text.open("output.txt", FileIO.WRITE);

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")))

COBOL

Works with: GnuCOBOL

and other compilers with the system call extensions

       identification division.
       program-id. create-a-file.

       data division.
       working-storage section.
       01 skip                 pic 9 value 2.
       01 file-name.
          05 value "/output.txt".
       01 dir-name.
          05 value "/docs".
       01 file-handle          usage binary-long.

       procedure division.
       files-main.

      *> create in current working directory
       perform create-file-and-dir

      *> create in root of file system, will fail without privilege
       move 1 to skip
       perform create-file-and-dir

       goback.

       create-file-and-dir.
      *> create file in current working dir, for read/write
       call "CBL_CREATE_FILE" using file-name(skip:) 3 0 0 file-handle
       if return-code not equal 0 then
           display "error: CBL_CREATE_FILE " file-name(skip:) ": "
                   file-handle ", " return-code upon syserr
       end-if

      *> create dir below current working dir, owner/group read/write
       call "CBL_CREATE_DIR" using dir-name(skip:)
       if return-code not equal 0 then
           display "error: CBL_CREATE_DIR " dir-name(skip:) ": "
                   return-code upon syserr
       end-if
       .

       end program create-a-file.
Output:
prompt$ cobc -xj create-a-file.cob
error: CBL_CREATE_FILE /output.txt: -0000000001, +000000035
error: CBL_CREATE_DIR /docs: +000000128

Errors due to running sample without root permissions.

prompt$ ls -larct
...
-rw-rw-r--  1 rosetta rosetta   1279 Jun  1 08:14 create-a-file.cob
-rwxrwxr-x  1 rosetta rosetta  13896 Jun  1 08:17 create-a-file
-rw-rw-r--  1 rosetta rosetta      0 Jun  1 08:17 output.txt
drwxrwx---  2 rosetta rosetta   4096 Jun  1 08:17 docs
drwxrwxr-x  5 rosetta rosetta  12288 Jun  1 08:17 .

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/")))

Component Pascal

MODULE CreateFile;
IMPORT Files, StdLog;

PROCEDURE Do*;
VAR
	f: Files.File;
	res: INTEGER;
BEGIN
	f := Files.dir.New(Files.dir.This("docs"),Files.dontAsk);
	f.Register("output","txt",TRUE,res);
	f.Close();
	
	f := Files.dir.New(Files.dir.This("C:\AEAT\docs"),Files.dontAsk);
	f.Register("output","txt",TRUE,res);
	f.Close()
END Do;

END CreateFile.

Crystal

File.write "output.txt", ""
Dir.mkdir "docs"

File.write "/output.txt", ""
Dir.mkdir "/docs"

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") ;
}

Dc

! for d in . / ;do > "$d/output.txt" ; mkdir "$d/docs" ;done

DCL

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

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.

E

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

EchoLisp

;; The file system is the browser local storage
;; It is divided into named stores (directories)
;; "user" is the default (home) store

; before : list of stores
(local-stores)  ("system" "user" "words" "reader" "info" "root") 

(local-put-value "output.txt" "")  "output.txt" ; into "user"
(local-make-store "user/docs")  "user/docs"
(local-put-value "output.txt" "" "root")  "output.txt" ; into "root"
(local-make-store 'root/docs)  "root/docs"

; after : list of stores
(local-stores 'root)  ("root" "root/docs")
(local-stores 'user)  ("user" "user/docs")

ed

While one can create files with ed-native commands, creating directories requires reaching out to the shell.

# by Artyom Bologov
H
w output.txt
!mkdir docs/
w /output.txt
!mkdir /docs/
Q

Elena

ELENA 4.x :

import system'io;
 
public program()
{ 
    File.assign("output.txt").textwriter().close();
 
    File.assign("\output.txt").textwriter().close();        
 
    Directory.assign("docs").create();
 
    Directory.assign("\docs").create();
}

Elixir

File.open("output.txt", [:write])
File.open("/output.txt", [:write])

File.mkdir!("docs")
File.mkdir!("/docs")

Emacs Lisp

(make-empty-file "output.txt")
(make-directory "docs")
(make-empty-file "/output.txt")
(make-directory "/docs")

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"]) ).

ERRE

Filenames are in 8+3 DOS format: without drive and directory info, refer to the same directory as the ERRE program is running from; full pathnames can include drive name and directory. You must use PC.LIB for managing directories.

PROGRAM FILE_TEST

!$INCLUDE="PC.LIB"

BEGIN

    OPEN("O",#1,"output.txt")
    CLOSE(1)
 
    OS_MKDIR("C:\RC")   ! with the appropriate access rights .......
    OPEN("O",#1,"C:\RC\output.txt")
    CLOSE(1)

END PROGRAM

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)

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

Factor

USE: io.directories

"output.txt" "/output.txt" [ touch-file ] bi@
"docs" "/docs" [ make-directory ] bi@

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!"
  }  
}

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

Fortran

Works with: Fortran version 90 and later

Don't know a way of creating directories in Fortran

  1. Edit: Use system commands to create directories
PROGRAM CREATION
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)

!Directories (Use System from GNU Fortran Compiler)
! -- Added by Anant Dixit, November 2014
call system("mkdir docs/")
call system("mkdir ~/docs/")

END PROGRAM

FreeBASIC

' FB 1.05.0 Win64

' create empty file and sub-directory in current directory
Open "output.txt" For Output As #1
Close #1
MkDir "docs"

' create empty file and sub-directory in root directory c:\
' creating file in root requires administrative privileges in Windows 10
Open "c:\output.txt" For Output As #1
Close #1
MkDir "c:\docs"

Print "Press any key to quit"
Sleep

friendly interactive shell

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

FunL

Translation of: Scala
import io.File

File( 'output.txt' ).createNewFile()
File( File.separator + 'output.txt' ).createNewFile()
File( 'docs' ).mkdir()
File( File.separator + 'docs' ).mkdir()

FutureBasic

include "NSLog.incl"

CFURLRef url

url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@"~/Desktop/output.txt") )
if (fn FileManagerCreateFileAtURL( url, NULL, NULL ) )
  NSLog( @"File \"output.txt\" created." )
else
  NSLog( @"Unable to create file \"output.txt\"." )
end if

url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@"~/Desktop/docs") )
if (fn FileManagerCreateDirectoryAtURL( url, YES, NULL ) )
  NSLog( @"Directory \"docs\" created." )
else
  NSLog( @"Unabled to create directory \"docs\"." )
end if

HandleEvents

Gambas

Click this link to run this code

Public Sub Main()
Dim byCount As Byte
Dim sToSave As String

For byCount = 0 To 50
  sToSave &= Format(Str(byCount), "00") & " - Charlie was here!" & gb.NewLine
Next

File.Save(User.Home &/ "TestFile", sToSave)
Print File.Load(User.Home &/ "TestFile")

End

Output:

00 - Charlie was here!
01 - Charlie was here!
02 - Charlie was here!
03 - Charlie was here!
04 - Charlie was here!
.........

Go

package main

import (
    "fmt"
    "os"
)

func createFile(fn string) {
    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")
}

Groovy

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

Haskell

import System.Directory

createFile name = writeFile name ""

main = do
  createFile "output.txt"
  createDirectory "docs"
  createFile "/output.txt"
  createDirectory "/docs"

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

i

software {
	create("output.txt")
	create("docs/")
	create("/output.txt")
	create("/docs/")
}

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.

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.)

See Also

Java

import java.io.File;
import java.io.IOException;
void create() throws IOException {
    File file = new File("output.txt");
    /* create an empty file */
    file.createNewFile();
    File directory = new File("docs/");
    /* create all parent directories */
    directory.mkdirs();
    File rootDirectory = new File("/docs/");
    rootDirectory.mkdirs();
}


An alternate implementation

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());
		}
	}
}

Using Java version 11

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public final class CreateAFile {

	public static void main(String[] args) throws IOException {
		Files.createFile(Path.of("output.txt"));		
		Files.createDirectory(Path.of("docs"));
		
		Files.createFile(Path.of("/output.txt"));
		Files.createDirectory(Path.of("/docs"));
	}

}

JavaScript

Works with: Node.js
const fs = require('fs');

function fct(err) {
  if (err) console.log(err);
}

fs.writeFile("output.txt", "", fct);
fs.writeFile("/output.txt", "", fct);

fs.mkdir("docs", fct);
fs.mkdir("/docs", fct);

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)

Julia

# many I/O functions have UNIX names

touch("output.txt")
mkdir("docs")

# probably don't have permission
try
    touch("/output.txt")
    mkdir("/docs")
catch e
    warn(e)
end

K

Directory creation is OS-dependent

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

Kotlin

/* testing on Windows 10 which needs administrative privileges
   to create files in the root */

import java.io.File

fun main(args: Array<String>) {
    val filePaths = arrayOf("output.txt", "c:\\output.txt")
    val dirPaths  = arrayOf("docs", "c:\\docs")
    var f: File
    for (path in filePaths) {
        f = File(path)
        if (f.createNewFile())
            println("$path successfully created")
        else
            println("$path already exists")
    }
    for (path in dirPaths) {
        f = File(path)
        if (f.mkdir())
            println("$path successfully created")
        else
            println("$path already exists")
    }
}
Output:
output.txt successfully created
c:\output.txt successfully created
docs successfully created
c:\docs successfully created

Running program again after files created :

Output:
output.txt already exists
c:\output.txt already exists
docs already exists
c:\docs already exists

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.

Lang

# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)

$file1 = [[io]]::fp.openFile(output.txt)
[[io]]::fp.createFile($file1)
[[io]]::fp.closeFile($file1)

$file2 = [[io]]::fp.openFile(/output.txt)
[[io]]::fp.createFile($file2)
[[io]]::fp.closeFile($file2)

$dir1 = [[io]]::fp.openFile(docs)
[[io]]::fp.makeDirectory($dir1)
[[io]]::fp.closeFile($dir1)

$dir2 = [[io]]::fp.openFile(/docs)
[[io]]::fp.makeDirectory($dir2)
[[io]]::fp.closeFile($dir2)

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

LFE

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

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

Lingo

Create an empty file in cwd:

-- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp.createFile("output.txt")

Create empty file in root of current volume:

-- note: fileIO xtra is shipped with Director, i.e. an "internal"
pd = the last char of _movie.path -- "\" for win, ":" for mac
_player.itemDelimiter = pd
vol = _movie.path.item[1]
fp = xtra("fileIO").new()
fp.createFile(vol&pd&"output.txt")

Creating an empty directory requires a 3rd party xtra, but there are various free xtras that allow this. Here as example usage of Shell xtra:

shell_cmd("mkdir Docs") -- in cwd, both win and mac
shell_cmd("mkdir \Docs") -- win
shell_cmd("mkdir /Docs") -- mac

Little

We are going to use /tmp instead the root.

void create_file(string path) {
    FILE f;
    unless (exists(path)) {
        unless (f = fopen(path, "w")){
            die(path);
        } else {
            puts("file ${path} created");
            fclose(f);
        }
    } else {
        puts("File ${path} already exists");
    }
}

void create_dir(string path) {
    unless (exists(path)) {
        unless(mkdir(path)) { //mkdir returns 0 on success, -1 on error
            puts("directory ${path} created");
        } else {
            puts(stderr, "Error: directory ${path} not created");   
        }
    } else {
        puts("directory ${path} already exists");
    }
}

create_file("output.txt");
create_file("/tmp/output.txt");
create_dir("docs");
create_dir("/tmp/docs");

Lua

Works with: Lua version 5.1

Create File

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

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")

M2000 Interpreter

Create directory and a file in two directories. First we look if places are in Drive Fixed.

If ok then we look if directory exist and if not then we make it

We check the time stamp of directory

Next we make an empty file, and get the time stamp of it

We use a Sub as Task(). Subs can view everything in Module. This not hold for modules, a module can't see anything outside in either way, for parent module or child module, with one exception, a module in a Group can see other members in that group, if they are in same level, or public members from children groups, lower levels (upper levels are not aware for modules).

In subs we have to use Local to make local variables, that can be shadow local variables with same name in module.

We can use Try {Print str$(File.Stamp("output.txt"), "YYYY|MM|DD|hh:nn:ss")} so if file not exist nothing printed and error dropped from Try block.

Work nice in Ubuntu using Wine.

In Windows 10 we have to open M2000 environment (m2000.exe) with elevated privileges to have write access directly in root directory (so without it, we get error from task(RootDir$))


Module MakeDirAndFile {
      Def WorkingDir$, RootDir$
      If Drive$(Dir$)="Drive Fixed" Then WorkingDir$=Dir$
      If Drive$("C:\")="Drive Fixed" Then RootDir$="C:\"
      
      if WorkingDir$<>"" Then task(WorkingDir$)
      If RootDir$<>"" then task(RootDir$)
      Dir User ' return to user directory
      
      Sub task(WorkingDir$)
            Dir WorkingDir$
            If Not Exist.Dir("docs") then SubDir "docs" : Dir WorkingDir$
            If Exist.Dir("docs") Then Print str$(File.Stamp("docs"), "YYYY|MM|DD|hh:nn:ss")
            Open "output.txt" For Output as #F
            Close #f
            If Exist("output.txt") Then Print str$(File.Stamp("output.txt"), "YYYY|MM|DD|hh:nn:ss")
      End Sub
}
MakeDirAndFile

M6809 Assembler

        nam     create_file
        ttl     M6809 Program to create a file and a directory
*
*       M6809 Assembler running under the OS-9 Operating System
*             built with:  asm cf.a L O=cf #32k
*
        ifp1
        use     /DD/defs/os9.d
        endc
*
        mod     PRGSIZ,PRGNAM,TYPE,REVS,START,SIZE
PRGNAM  fcs     /cf/
TYPE    set     Prgrm+Objct
REVS    set     ReEnt+1

HEREF   fcs     './output.txt'
        fcb     $0D
ROOTF   fcs     '/dd/output.txt'
        fcb     $0D
HERED   fcs     './docs'
        fcb     $0D
ROOTD   fcs     '/dd/docs'
        fcb     $0D
        rmb     250
        rmb     200
SIZE    equ     .
*
START   equ     *
        leax    HEREF,pcr
        lda     #UPDAT.
        ldb     #READ.+WRITE.+PREAD.+PWRIT.
        os9     I$Create
        leax    ROOTF,pcr
        lda     #UPDAT.
        ldb     #READ.+WRITE.+PREAD.+PWRIT.
        os9     I$Create
        leax    HERED,pcr
        lda     #UPDAT.
        ldb     #READ.+WRITE.+PREAD.+PWRIT.
        os9     I$MakDir
        leax    ROOTD,pcr
        lda     #UPDAT.
        ldb     #READ.+WRITE.+PREAD.+PWRIT.
        os9     I$MakDir
        clrb
        os9     F$Exit
        emod
PRGSIZ  equ     *
        END

Maple

FileTools:-Text:-WriteFile("output.txt", "");  # make empty file in current dir
FileTools:-MakeDirectory("docs");               # make empty dir in current dir
FileTools:-Text:-WriteFile("/output.txt", ""); # make empty file in root dir
FileTools:-MakeDirectory("/docs");              # make empty dir in root dir

Mathematica / Wolfram Language

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"]
(*"left<>right" is shorthand for "StringJoin[left,right]"*)

MATLAB / Octave

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

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/"))

MAXScript

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

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).

Mirah

import java.io.File

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

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.

Nanoquery

import Nanoquery.IO

f = new(File)
f.create("output.txt")
f.createDir("docs")

// in the root directory
f.create("/output.txt")
f.createDir("/docs")

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
    }
}

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

Nim

import os

open("output.txt", fmWrite).close()
createDir("docs")

open(DirSep & "output.txt", fmWrite).close()
createDir(DirSep & "docs")
Translation of: Python
import os
const directories = ["/", "./"]
for directory in directories:
  open(directory & "output.txt", fmWrite).close()
  createDir(directory & "docs")

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");
    }
  }
}

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];

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")

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

PARI/GP

Creating an empty file in GP requires write1 rather than write to avoid the automatic newline.

write1("0.txt","")
write1("/0.txt","")

GP cannot, itself, create directories; for that, you would need PARI (where the solution would follow those in C) or system:

system("mkdir newdir")

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;

PascalABC.NET

##
var f: textfile;
assignFile(f, '/output.txt');
rewrite(f);
close(f);
createdir('/docs');
assignFile(f, '/docs/output.txt');
rewrite(f);
close(f);

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 Raku

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);

Phix

Copy of Euphoria, modified to display a warning when it cannot create a file in the system root (as such is typically banned on more recent operating systems)

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")
if fn=-1 then
    puts(1,"unable to create \\output.txt\n")
else
    close(fn)
end if

Phixmonti

"foo.bar" "w" fopen fclose

PHP

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

PicoLisp

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

Pike

import Stdio;

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

PL/I

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

Plain English

When I tested this program, it did not create "output.txt" in the filesystem root.

To run:
Start up.
\ In the current working directory
Create ".\output.txt" in the file system.
Create ".\docs\" in the file system.
\ In the filesystem root
Create "C:\output.txt" in the file system.
Create "C:\docs\" in the file system.
Shut down.

PowerShell

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

ProDOS

makedirectory docs
changedirectory docs
makenewfile output.txt

PureBasic

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

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

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")

Racket

#lang racket

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

Raku

(formerly Perl 6)

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

Raven

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

REBOL

; Creating in current directory:

write %output.txt ""
make-dir %docs/

; Creating in root directory:

write %/output.txt ""
make-dir %/docs/

Retro

There are no facilities in Retro to create directories.

'output.txt file:W file:open file:close
'/output.txt file:W file:open file:close

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.*/

Ring

system("mkdir C:\Ring\docs")
fopen("C:\Ring\docs\output.txt", "w+")
system("mkdir docs")
fopen("output.txt", "w+")

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
}

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

Rust

use std::io::{self, Write};
use std::fs::{DirBuilder, File};
use std::path::Path;
use std::{process,fmt};

const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";

fn main() {
    create(".").and(create("/"))
               .unwrap_or_else(|e| error_handler(e,1));
}


fn create<P>(root: P) -> io::Result<File>
    where P: AsRef<Path>
{
    let f_path = root.as_ref().join(FILE_NAME);
    let d_path = root.as_ref().join(DIR_NAME);
    DirBuilder::new().create(d_path).and(File::create(f_path))
}

fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "Error: {}", error);
    process::exit(code)
}

S-BASIC

CP/M (the only operating system supported by S-BASIC) does not have named directories or a

tree-structured file system. The closest thing to a "root" directory would be user area 0 on

drive A:, which on a stock system will be the logged in directory on a cold boot. The "call"

statement, which normally serves to invoke an assembly language routine, is here used to

call upon the BDOS to switch to the desired directory.

 
rem --  Set the logged drive ('A' to 'P')
procedure setdrive (drive = char)
   var hl, de, bc, a_psw = integer
   rem -- ensure drive letter is upper case
   if drive >= 'a' then drive = drive - 32
   hl = 0
   de = drive - 65
   bc = 0EH  rem BDOS set drive function
   a_psw = 0
   rem - call BDOS with drive number in DE
   call (5H,hl,de,bc,a_psw)
end

rem  -- Set the CP/M user area (0 to 15)
procedure setuser (user = integer)
   var hl, bc, a_psw = integer
   hl = 0
   bc = 20H  rem BDOS set user function 
   a_psw = 0
   rem - call BDOS with user number in DE
   call (5H,hl,user,bc,a_psw)
end

comment
   create empty file "output.txt" in current directory and in
   startup directory (drive A:, user 0)
end

create "OUTPUT.TXT"
setdrive 'A'
setuser 0
create "OUTPUT.TXT"

end


Scala

Library: Scala
import java.io.File

object CreateFile extends App {
  try { new File("output.txt").createNewFile() }
  catch { case e: Exception => println(s"Exception caught: $e with creating output.txt") }
  try { new File(s"${File.separator}output.txt").createNewFile() }
  catch { case e: Exception => println(s"Exception caught: $e with creating ${File.separator}output.txt") }
  try { new File("docs").mkdir() }
  catch { case e: Exception => println(s"Exception caught: $e with creating directory docs") }
  try { new File(s"${File.separator}docs").mkdir() }
  catch { case e: Exception => println(s"Exception caught: $e with creating directory ${File.separator}docs") }
}

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.

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);
    makeDir("docs");
    aFile := open("/output.txt", "w");
    close(aFile);
    makeDir("/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".

SenseTalk

set the folder to "~/Desktop"
put "" into file "docs/output.txt"
set the folder to "/"
put empty into file "/docs/output.txt"

Or without defining a working directory:

put empty into file "~/Desktop/docs/output.txt"
put "" into file "/docs/output.txt"

Or using the Create command:

create file "output.txt"
create folder "docs"

Sidef

# Here
%f'output.txt' -> create;
%d'docs'       -> create;

# Root dir
Dir.root + %f'output.txt' -> create;
Dir.root + %d'docs'       -> create;

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.

Slope

Local:

(close (file-open-write "output.txt"))
(mkdir "docs" 0755)

Root:

(close (file-open-write "/output.txt"))
(mkdir "/docs" 0755)

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'.

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

SQL PL

Works with: Db2 LUW

version 9.7 or higher.

With SQL PL:

BEGIN
  DECLARE UTL_FILE_HANDLER UTL_FILE.FILE_TYPE;
  DECLARE DIR_ALIAS_CURRENT VARCHAR(128);
  DECLARE DIR_ALIAS_ROOT VARCHAR(128);
  DECLARE DIRECTORY VARCHAR(1024);
  DECLARE FILENAME VARCHAR(255);

  SET DIR_ALIAS_CURRENT = 'outputFileCurrent';
  SET DIRECTORY = '/home/db2inst1/doc';
  SET FILENAME = 'output.txt';

  CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_CURRENT, DIRECTORY);
  SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_CURRENT, FILENAME, 'a');
  CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);
  CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);

  SET DIR_ALIAS_ROOT = 'outputFileRoot';
  SET DIRECTORY = '/doc';

  CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_ROOT, DIRECTORY);
  SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_ROOT, FILENAME, 'a');
  CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);
  CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);
END @

The current directory notion does not exist in Db2. However, we can consider the home directory of the instance (in this case db2inst1) as current. For the directory under root, Db2 needs extra permissions to create a subdirectory at that level. Normally, that operation of creating a subdirectory at that level will raise an exception: "UTL_FILE.INVALID_OPERATION" SQLSTATE=58024.

Output:

db2 -td@
db2 => BEGIN
...
db2 (cont.) => END @
DB20000I  The SQL command completed successfully.
db2 => !ls /doc @
output.txt
db2 => !ls /home/db2inst1/doc @
output.txt

SQLite

/*
*Use '/' for *nix. Use whatever your root directory is on Windows. 
*Must be run as admin.
*/
.shell mkdir "docs";
.shell mkdir "/docs";
.output output.txt
.output /output.txt

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")

Stata

See the file command in Stata documentation. Note that Stata has other ways to store files: save to store a dataset in .dta format, or the various export commands to store a dataset as CSV, Excl, SAS XPORT 5 or XPORT 8 or dBase format.

file open f using output.txt, write replace
file close f
mkdir docs

file open f using \output.txt, write replace
file close f
mkdir \docs

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]

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

TUSCRIPT

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

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

Ursa

decl file f
f.create "output.txt"
f.createdir "docs"

# in the root directory
f.create "/output.txt"
f.createdir "/docs"

VBA

Public Sub create_file()
    Dim FileNumber As Integer
    FileNumber = FreeFile
    MkDir "docs"
    Open "docs\output.txt" For Output As #FreeFile
    Close #FreeFile
    MkDir "C:\docs"
    Open "C:\docs\output.txt" For Output As #FreeFile
    Close #FreeFile
End Sub

VBScript

Set objFSO = CreateObject("Scripting.FileSystemObject")

'current directory
objFSO.CreateFolder(".\docs")
objFSO.CreateTextFile(".\docs\output.txt")

'root directory
objFSO.CreateFolder("\docs")
objFSO.CreateTextFile("\docs\output.txt")

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")

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()

Visual Objects

//Use Library System Library

DirMake(String2Psz("c:\docs"))
FCreate("c:\docs\output.txt", FC_NORMAL)

Wren

To create a file in the root, assuming you have the necessary privileges, just change "output.txt" to "/output.txt" in the following script.

Wren does not currently support the creation of directories.

import "io" for File

// file is closed automatically after creation
File.create("output.txt") {}

// check size
System.print("%(File.size("output.txt")) bytes")
Output:
0 bytes

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

XPL0

XPL0 does not currently create directories. To create a file in the root directory, assuming you have permission, insert a slash at the beginning, like this: /output.txt

int FD;
FD:= FOpen("output.txt", 1);

Yabasic

open "output.txt" for writing as #1
close #1
 
system("mkdir " + "f:\docs")
if open(2, "f:\docs\output.txt") then
    print "Subdirectory or file already exists"
else 
    open "f:\docs\output.txt" for writing as #2
    close #2
end if

zkl

Works on Unix and Windows

$ ls -l docs
ls: cannot access docs: No such file or directory
$ zkl
zkl: fcn createOutputTxt(dir){ dir=dir+"/docs"; File.mkdir(dir); File(dir+"/output.txt","w") }
Void
zkl: createOutputTxt(".")
File(./docs/output.txt)                                                      
zkl: createOutputTxt("/")
Stack trace for VM#1 ():
   Cmd.createOutputTxt@mkdir addr:16  args(1) reg(0) 
   Cmd.__constructor@createOutputTxt addr:9  args(0) reg(0) R
   startup.__constructor addr:2271  args(0) reg(1) ER
   startup.__constructor addr:2207  args(0) reg(22) 
Exception thrown: IOError(File.mkdir(//docs): Permission denied)
zkl: ^D
$ ls -l docs
total 0
-rw-r--r-- 1 craigd craigd 0 Oct 27 22:08 output.txt

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
Cookies help us deliver our services. By using our services, you agree to our use of cookies.