Create a file

From Rosetta Code
Revision as of 13:27, 23 September 2010 by rosettacode>Mwn3d (→‎{{header|Java}}: This version is simpler and actually works)
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.

4DOS Batch

<lang 4dos>echos > output.txt mkdir docs

echos > \output.txt mkdir \docs</lang>

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.

<lang ada>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;</lang>

Aikido

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

</lang>

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. <lang algol68>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);

)</lang>

APL

<lang APL> 'output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums

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

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. <lang AppleScript >close (open for access "output.txt")</lang> Create a new folder (directory) on the startup disk (root directory). <lang AppleScript >tell application "Finder" to make new folder at startup disk with properties {name:"docs"}</lang> Create a zero-byte text file in the frontmost (open) Finder window. <lang AppleScript >tell application "Finder" to set wd to target of window 1 as string close (open for access wd & "output.txt")</lang> Create a new folder (directory) in the frontmost (open) Finder window. <lang AppleScript >tell application "Finder" to make new folder at window 1 with properties {name:"docs"}</lang> --Apl.way 21:20, 9 June 2010 (UTC)

AutoHotkey

<lang AutoHotkey>FileAppend,,output.txt FileCreateDir, docs FileAppend,,c:\output.txt FileCreateDir, c:\docs</lang>

AWK

There's no way to create a directory, except by calling an extern program (like mkdir) to do so. <lang awk>BEGIN {

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

}</lang>

BASIC

<lang qbasic>OPEN "output.txt" FOR OUTPUT AS 1 CLOSE OPEN "\output.txt" FOR OUTPUT AS 1 CLOSE</lang>

Batch File

<lang dos>copy nul output.txt copy nul \output.txt</lang>

<lang dos>md docs md \docs</lang>

C

ISO C (directory creation not supported): <lang c>#include <stdio.h>

int main() {

 FILE *fh = fopen("output.txt", "w");
 fclose(fh);
 return 0;

}</lang>

POSIX:

Works with: POSIX

<lang c>#include <sys/stat.h>

int main() {

 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;

}</lang>

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

C++

Uses some Microsoft library: <lang cpp>#include <fstream>

  1. 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; }</lang>

C#

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

}</lang>

Clojure

<lang lisp>(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")))</lang>

Common Lisp

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

 (close stream))</lang>

but it is more common to use with-open-file which has better exception handling. <lang lisp>(with-open-file (stream "output.txt" :direction :output)

   ;; use the stream here
)</lang>

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 <lang lisp>(let ((paths (list (make-pathname :directory '(:relative "docs"))

                    (make-pathname :directory '(:absolute "docs")))))
 (mapcar #'ensure-directories-exist paths))</lang>

So creating a file called output.txt with an absolute path in the root directory becomes: <lang lisp>(with-open-file

   (stream 
       (make-pathname :directory '(:absolute "") :name "output.txt")
       :direction :output))</lang>

On the other hand, if you may depend on the platform's pathname syntax then shorter notation may be used: <lang lisp>(mapcar #'ensure-directories-exist '(#p"docs/" #p"/docs/")))</lang>

D

For file creation, std.file.write function & std.stream.file class are used.
For dir creation, std.file.mkdir is used. <lang d>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") ;

}</lang>

DCL

<lang DCL>open/write output_file output.txt open/write output_file [000000]output.txt create/directory [.docs] create/directory [000000.docs]</lang>

E

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

Factor

<lang factor>USE: io.directories

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

Fancy

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

}</lang>

Forth

There is no means to create directories in ANS Forth. <lang forth> s" output.txt" w/o create-file throw ( fileid) drop s" /output.txt" w/o create-file throw ( fileid) drop</lang>

Fortran

Works with: Fortran version 90 and later

Don't know a way of creating directories in Fortran <lang 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)</lang>

Haskell

<lang haskell>import System.Directory

createFile name = writeFile name ""

main = do

 createFile "output.txt"
 createDirectory "docs"
 createFile "/output.txt"
 createDirectory "/docs"</lang>

HicEst

<lang 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 </lang>

Icon and Unicon

Icon

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.

Unicon

<lang Unicon>every dir := !["./","/"] do {

  close(open(f := dir || "input.txt","w"))  |stop("failure for open ",f)
  mkdir(f := dir || "docs")                 |stop("failure for mkdir ",f)
  }</lang>

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.

<lang j> 1!:2 <'/output.txt' NB. write an empty file

  1!:5 <'/docs'         NB. create a directory</lang>

However a number of libraries provide a more convenient/conventional interface to that underlying functionality. <lang j>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'</lang>

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

<lang 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"); new File("docs").mkdir(); new File(File.separator + "docs").mkdir(); } catch (IOException e) { System.err.println(e.getMessage()); } } }lang>

JavaScript

Works with: JScript

<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");

fso.CreateTextFile('output.txt').Close(); fso.CreateTextFile('c:/output.txt').Close();

fso.CreateFolder('docs'); fso.CreateFolder('c:/docs');</lang>


Lua

Works with: Lua version 5.1

Create File

<lang lua> io.open("output.txt", "w"):close() io.open("\\output.txt", "w"):close() </lang>

Create Directory

This solution sends the command to the OS shell.

<lang lua> os.execute("mkdir docs") os.execute("mkdir \\docs") </lang>

Mathematica

<lang Mathematica> SetDirectory@NotebookDirectory[]; t = OpenWrite["output.txt"] Close[t] s = OpenWrite["D:\output.txt"] Close[s]

</lang>

MAXScript

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

Modula-3

<lang modula3>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.</lang>

Objective-C

<lang objc>NSFileManager *fm = [NSFileManager defaultManager];

[fm createFileAtPath:@"output.txt" contents:[NSData data] attributes:nil]; [fm createDirectoryAtPath:@"docs" attributes:nil];</lang>

Objeck

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

} </lang>

OCaml

<lang ocaml># let oc = open_out "output.txt" in

 close_out oc;;

- : unit = ()

  1. Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *)

- : unit = ()</lang>

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

Oz

<lang 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</lang>


Pascal

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

<lang pascal-delphi> 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; </lang>


Perl

<lang 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';

};</lang>

Without Perl Modules

Current directory <lang perl>perl -e 'qx(touch output.txt)' perl -e 'mkdir docs'</lang>

Root directory <lang perl>perl -e 'qx(touch /output.txt)' perl -e 'mkdir "/docs"'</lang>

PHP

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

PicoLisp

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

Pike

<lang pike>import Stdio;

int main(){

  write_file("input.txt","",0100);
  write_file("/input.txt","",0100);

}</lang>

PL/I

<lang PL/I> open file (output) title ('/OUTPUT.TXT,type(text),recsize(100)' ); close file (output); </lang>

PowerShell

<lang powershell>New-Item output.txt -ItemType File New-Item \output.txt -ItemType File New-Item docs -ItemType Directory New-Item \docs -ItemType Directory</lang>

PureBasic

<lang PureBasic>CreateFile(0,"output.txt"):CloseFile(0) CreateDirectory("docs") CreateFile(0,"/output.txt"):CloseFile(0) CreateDirectory("/docs")</lang>

Python

<lang python>import os for dir in ['/', './']:

 open(directory + 'output.txt', 'w').close()  # create /output.txt, then ./output.txt
 os.mkdir(directory + 'docs')                 # create directory /docs, then ./docs</lang>
Works with: Python version 2.5

Exception-safe way to create file:

<lang python>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</lang>

R

<lang R>f <- file("output.txt", "w") close(f)

  1. it may fails and the exact syntax to achieve the root
  2. changes according to the operating system

f <- file("/output.txt", "w") close(f)

success <- dir.create("docs") success <- dir.create("/docs")</lang>

Raven

<lang raven>"" as str str 'output.txt' write str '/output.txt' write 'docs' mkdir '/docs' mkdir</lang>

Ruby

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

}</lang>

Scheme

<lang scheme>(open-output-file "output.txt") (open-output-file "/output.txt")</lang> 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.

Slate

File creation locally: <lang slate>(File newNamed: 'output.txt') touch. (Directory current / 'output.txt') touch.</lang>

File creation at root: <lang slate>(File newNamed: '/output.txt') touch. (Directory root / 'output.txt') touch.</lang>

Smalltalk

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

<lang smalltalk>(FileDirectory on: 'c:\') newFileNamed: 'output.txt'; createDirectory: 'docs'.</lang>

In GNU Smalltalk you can do instead:

<lang smalltalk>ws := (File name: 'output.txt') writeStream. ws close. Directory create: 'docs'.

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

SNOBOL4

Works with: Macro Spitbol
Works with: CSnobol

<lang SNOBOL4> 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</lang>

Standard ML

<lang sml>let val out = TextIO.openOut "output.txt" in

 TextIO.closeOut out

end;

OS.FileSys.mkDir "docs";</lang>

(for creation in the filesystem root, replace the filenames by "/output.txt" and "/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):

<lang tcl>close [open output.txt w] close [open [file nativename /output.txt] w]

file mkdir docs file mkdir [file nativename /docs]</lang>

Toka

<lang 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</lang>

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. <lang vedit>// 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")</lang>

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vbnet> '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()</lang>

UNIX Shell

Works with: bash

<lang bash>touch {/,}output.txt # create both /output.txt and output.txt mkdir {/,}docs # create both /docs and docs</lang>

X86 Assembly

Works with: NASM version Linux

<lang asm>

syscall numbers for readability.
]

%define sys_mkdir 39 %define sys_creat 8

section .text global _start

_start: mov ebx, dn mov eax, sys_mkdir mov ecx, 0750Q ;permission(rw_rw_rw) int 0x80

mov ebx, fn mov eax, sys_creat mov ecx, 0640Q int 0x80 test eax, eax js _ragequit ;jump is less than zero

mov ebx, rfn mov eax, sys_creat mov ecx, 00777Q int 0x80 cmp eax, 0 jle _exit

_ragequit: mov edx, err_len mov ecx, err_msg mov ebx, 4 mov eax ,1 int 0x80

_exit: push 0x1 mov eax, 1 push eax int 0x80 ret

section .data fn db 'doc/output.txt',0 rfn db '/output.txt',0 dn db 'doc',0

err_msg db "Something went wrong! :[",0xa err_len equ $-err_msg </lang>