Create a file: Difference between revisions

From Rosetta Code
Content added Content deleted
m (<code>)
m (<lang>)
Line 54: Line 54:
=={{header|C}}==
=={{header|C}}==


<code c>
<lang c>
#include <stdio.h>
#include <stdio.h>


Line 63: Line 63:
return 0;
return 0;
}
}
</code>
</lang>


{{works with|POSIX}}
{{works with|POSIX}}
<code c>
<lang c>
#include <sys/stat.h>
#include <sys/stat.h>


Line 74: Line 74:
return 0;
return 0;
}
}
</code>
</lang>


(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")
(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")
Line 81: Line 81:
For file creation, std.file.write function & std.stream.file class are used.<br>
For file creation, std.file.write function & std.stream.file class are used.<br>
For dir creation, std.file.mkdir is used.
For dir creation, std.file.mkdir is used.
<code d>
<lang d>
module fileio ;
module fileio ;
import std.stdio ;
import std.stdio ;
Line 128: Line 128:
testCreate("output.txt", "docs") ;
testCreate("output.txt", "docs") ;
}
}
</code>
</lang>


=={{header|DOS Batch File}}==
=={{header|DOS Batch File}}==
Line 142: Line 142:
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
Don't know a way of creating directories in Fortran
Don't know a way of creating directories in Fortran
<code fortran>
<lang fortran>
OPEN (UNIT=5, FILE="output.txt", STATUS="NEW") ! Current directory
OPEN (UNIT=5, FILE="output.txt", STATUS="NEW") ! Current directory
CLOSE (UNIT=5)
CLOSE (UNIT=5)
OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") ! Root directory
OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") ! Root directory
CLOSE (UNIT=5)
CLOSE (UNIT=5)
</code>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==


<code haskell>
<lang haskell>
import System.Directory
import System.Directory


Line 161: Line 161:
createFile "/output.txt"
createFile "/output.txt"
createDirectory "/docs"
createDirectory "/docs"
</code>
</lang>


=={{header|Java}}==
=={{header|Java}}==


<code java5>
<lang java5>
import java.util.File;
import java.util.File;
public class CreateFileTest {
public class CreateFileTest {
Line 193: Line 193:
}
}
}
}
</code>
</lang>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
Line 207: Line 207:
=={{header|OCaml}}==
=={{header|OCaml}}==


<code ocaml>
<lang ocaml>
# let oc = open_out "output.txt" in
# let oc = open_out "output.txt" in
close_out oc;;
close_out oc;;
Line 214: Line 214:
# Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *)
# Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *)
- : unit = ()
- : unit = ()
</code>
</lang>


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


=={{header|Perl}}==
=={{header|Perl}}==
<code perl>
<lang perl>
use File::Spec::Functions qw(catfile rootdir);
use File::Spec::Functions qw(catfile rootdir);
{ # here
{ # here
Line 229: Line 229:
mkdir catfile rootdir, 'docs';
mkdir catfile rootdir, 'docs';
};
};
</code>
</lang>


'''Without Perl Modules'''
'''Without Perl Modules'''


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


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


=={{header|Python}}==
=={{header|Python}}==
Line 249: Line 249:
Current directory
Current directory


<code python>
<lang python>
import os
import os
f = open("output.txt", "w")
f = open("output.txt", "w")
f.close()
f.close()
os.mkdir("docs")
os.mkdir("docs")
</code>
</lang>


Root directory
Root directory


<code python>
<lang python>
f = open("/output.txt", "w")
f = open("/output.txt", "w")
f.close()
f.close()
os.mkdir("/docs")
os.mkdir("/docs")
</code>
</lang>


{{works with|Python|2.5}}
{{works with|Python|2.5}}
Exception-safe way to create file:
Exception-safe way to create file:


<code python>
<lang python>
from __future__ import with_statement
from __future__ import with_statement
import os
import os
Line 277: Line 277:
create(".") # current directory
create(".") # current directory
create("/") # root directory
create("/") # root directory
</code>
</lang>


=={{header|Raven}}==
=={{header|Raven}}==
Line 289: Line 289:
=={{header|Ruby}}==
=={{header|Ruby}}==


<code ruby>
<lang ruby>
#Current directory
#Current directory
open("output.txt", "w") { }
open("output.txt", "w") { }
Line 297: Line 297:
open("/output.txt", "w") { }
open("/output.txt", "w") { }
Dir.mkdir("/docs")
Dir.mkdir("/docs")
</code>
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 303: Line 303:
Squeak has no notion of 'current directory' because it isn't tied to the shell that created it.
Squeak has no notion of 'current directory' because it isn't tied to the shell that created it.


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


In [[GNU Smalltalk]] you can do instead:
In [[GNU Smalltalk]] you can do instead:


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


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 323: Line 323:
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):
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):


<code tcl>
<lang tcl>
close [open output.txt w]
close [open output.txt w]
close [open [file nativename /output.txt] w]
close [open [file nativename /output.txt] w]
Line 329: Line 329:
file mkdir docs
file mkdir docs
file mkdir [file nativename /docs]
file mkdir [file nativename /docs]
</code>
</lang>


=={{header|Toka}}==
=={{header|Toka}}==
Line 346: Line 346:


{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<code vb>
<lang vb>
'Current Directory
'Current Directory
IO.Directory.CreateDirectory("docs")
IO.Directory.CreateDirectory("docs")
Line 358: Line 358:
IO.Directory.CreateDirectory(IO.Path.DirectorySeparatorChar & "docs")
IO.Directory.CreateDirectory(IO.Path.DirectorySeparatorChar & "docs")
IO.File.Create(IO.Path.DirectorySeparatorChar & "output.txt").Close()
IO.File.Create(IO.Path.DirectorySeparatorChar & "output.txt").Close()
</code>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


<code bash>
<lang bash>
touch output.txt
touch output.txt
touch /output.txt
touch /output.txt
mkdir docs
mkdir docs
mkdir /docs
mkdir /docs
</code>
</lang>

Revision as of 13:31, 31 January 2009

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

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

C

<lang c>

  1. include <stdio.h>

int main() {

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

} </lang>

Works with: POSIX

<lang c>

  1. include <sys/stat.h>

int main() {

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

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>

DOS Batch File

 md docs
 md \docs

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

Java

<lang java5> import java.util.File; public class CreateFileTest {

  public static String createNewFile(String filename) {
      try {
          // Create file if it does not exist
          boolean success = new File(filename).createNewFile();
          if (success) {
              return " did not exist and was created successfully.";
          } else {
              return " already exists.";
          }
      } catch (IOException e) {
              return " could not be created.";
      }
  }
  public static void test(String type, String filename) {
      System.out.println("The following " + type + " called " + filename + 
          createNewFile(filename)
      );
  }
  public static void main(String args[]) {
       test("file", "output.txt");
       test("file", File.seperator + "output.txt");
       test("directory", "docs");
       test("directory", File.seperator + "docs" + File.seperator);
  }

} </lang>

MAXScript

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

OCaml

<lang ocaml>

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

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>

Python

Current directory

<lang python>

import os
f = open("output.txt", "w")
f.close()
os.mkdir("docs")

</lang>

Root directory

<lang python>

f = open("/output.txt", "w")
f.close()
os.mkdir("/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(dir):
    with open(os.path.join(dir, "output.txt"), "w"):
        pass
    os.mkdir(os.path.join(dir, "docs"))
   
create(".") # current directory
create("/") # root directory

</lang>

Raven

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

Ruby

<lang ruby>

  1. Current directory

open("output.txt", "w") { } Dir.mkdir("docs")

  1. Root directory

open("/output.txt", "w") { } Dir.mkdir("/docs") </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>

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

 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

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vb>

'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

<lang bash> touch output.txt touch /output.txt mkdir docs mkdir /docs </lang>