Create and write to a file

11

3

Challenge

Create a new file and write the string Hello World to it.

Restrictions

  • Your challenge must write to a file on disk, in the file system.

  • The file may not be a log file generated during normal operation of the interpreter.

  • The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

  • No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

  • This is , so shortest program in bytes wins.

  • Follow the spirit, not the letter, of the rules.

dkudriavtsev

Posted 2016-08-01T05:37:11.710

Reputation: 5 781

Is trailing newline okay? – Winny – 2016-08-01T09:03:23.150

@Winny yes, it is ok – dkudriavtsev – 2016-08-01T20:23:21.310

Is a filename part of the contents of a file? – CousinCocaine – 2016-08-12T20:36:54.683

Answers

1

Pyth, 14 bytes

.w"Hello World

Outputs to a file called o.txt.

Doorknob

Posted 2016-08-01T05:37:11.710

Reputation: 68 138

24

Python 2, 32 bytes

print>>open(*"ww"),"Hello World"

Yes, this is valid python.

xsot

Posted 2016-08-01T05:37:11.710

Reputation: 5 069

1Woah. Explanation? – James – 2016-08-01T06:22:49.947

1@DrGreenEggsandIronMan it looks like the main trick is how * can split an iterable into individual arguments in a function, so open(*"ww") becomes open("w","w"). – Value Ink – 2016-08-01T09:09:27.270

7@ValueInk Actually the main trick is the use of the extended print statement which is rarely seen in the wild. – xsot – 2016-08-01T10:20:37.893

1That is indeed a cool trick, but if it weren't for your *"ww" trick you'd've tied with the other Python answer here, which uses open(...).write(...) instead for the same byte count – Value Ink – 2016-08-01T10:23:33.823

Oops, I didn't even realise that. – xsot – 2016-08-01T10:26:55.227

8

Haskell, 25 bytes

writeFile"o""Hello World"

Anders Kaseorg

Posted 2016-08-01T05:37:11.710

Reputation: 29 242

6

zsh, 17 bytes

<<<Hello\ World>x

Outputs to a file called x.

Doorknob

Posted 2016-08-01T05:37:11.710

Reputation: 68 138

Can you interpreted the > as a pipe? – CousinCocaine – 2016-08-12T20:34:00.260

What about >Hello\ World – CousinCocaine – 2016-08-12T20:41:40.770

5

Vim, 15 + 2 == 17 bytes

iHello World<esc>ZZ

+2 bytes for launching this with vim f instead of vim. Additionally, this version works to:

iHello World<C-o>ZZ

If launching vim like this is not allowed, there is also:

Vim, 18 bytes

iHello World<esc>:w f<cr>

Side note: this is a polyglot. The same thing works in V, except that it is one byte shorter (since the <cr> at the end is implicit.)

James

Posted 2016-08-01T05:37:11.710

Reputation: 54 537

What's the f<cr> at the end for? – Zwei – 2016-08-01T06:05:31.060

@Zwei 'f' is the name of the file, and the <cr> (which is a mnemonic for "enter", a single byte) is necessary to run the command. Commands that start with a colon are like a mini shell inside of vim, and the command :w is the command for writing to a file. – James – 2016-08-01T06:08:47.370

Should <esc> not be counted as 5 bytes and <cr> as 4, since they have to be fully typed in? – Bart van Nierop – 2016-08-03T05:38:18.087

@BartvanNierop No, <esc> is just notation for "The escape key", which is 0x1B, and <cr> is notation for "The Carriage Return key" which is 0x0B – James – 2016-08-03T05:39:42.700

That's if you actually start vim and type it. As far as I'm aware, when you're writing the source code in vimscript, you have to type them out. – Bart van Nierop – 2016-08-03T05:44:49.460

1

Well first off, there is a precedent to score vim with keystrokes == bytes, but second off, there are several ways to write this in vim "code" without using the vim-key notation. For example, if you use <C-v> to insert a literal escape character and a literal carriage return, then you can assign all of these strokes to a macro, and run it that way. You could also do it in vimscript with normal 'iHello World^[:w f^M which is how vim displays it, not how you enter it. ^[ and ^M are both one byte.

– James – 2016-08-03T05:50:39.763

And so I learn something new (about vim) every day. =] Thanks for the thorough explanation. – Bart van Nierop – 2016-08-03T06:21:45.070

5

Ruby, 26 bytes

Writes to file f.

open(?f,?w)<<"Hello World"

Value Ink

Posted 2016-08-01T05:37:11.710

Reputation: 10 608

5

Batch, 18 bytes

echo Hello World>f

Shaun Wild

Posted 2016-08-01T05:37:11.710

Reputation: 2 329

I think you need an @, or re-title this as (console). – Erik the Outgolfer – 2016-10-02T18:13:33.503

The @ is not necessary. – Shaun Wild – 2016-10-03T08:07:34.587

Try saving it in a batch file and run it as such (not directly type the command). You will then see that you need the @, because the command is otherwise printed too. That means you have two options: 1) Delete this answer because it will be a dupe 2) Relabel as (console). – Erik the Outgolfer – 2016-10-03T10:35:55.977

4

Batch, 19 bytes

@echo Hello World>o

Neil

Posted 2016-08-01T05:37:11.710

Reputation: 95 035

Not sure if it counts as wrong, but it outputs "Hello World" and a newline to the file, rather than simply "Hello World" – brianush1 – 2016-08-01T12:18:59.177

What is the '@' good for? – PEAR – 2016-08-01T13:03:12.910

@PEAR It prevents the command from being echoed to STDOUT. – Neil – 2016-08-01T13:18:43.783

@brianush1 It doesn't count as wrong, apparently.

– Erik the Outgolfer – 2016-10-02T18:14:09.150

3

C, 44 bytes

main(){fputs("Hello World",fopen("o","w"));}

orlp

Posted 2016-08-01T05:37:11.710

Reputation: 37 067

1This will segfault on some systems without #include <stdio.h> – Steven Penny – 2016-08-01T12:23:40.580

@StevenPenny As long as there's a system/compiler where it's guaranteed not to segfault, that's fine. Answers generally don't have to be portable. – Martin Ender – 2016-10-02T20:57:41.440

@StevenPenny And now it has.

– orlp – 2016-10-03T05:54:05.190

3

PowerShell, 15 bytes

"Hello World">o

> redirects the string to a file called o in the current directory.

Ben Owen

Posted 2016-08-01T05:37:11.710

Reputation: 111

2

Dyalog APL, 19 bytes

⎕NPUT⍨'Hello World'

Creates a file with the name and contents "Hello World".

Adám

Posted 2016-08-01T05:37:11.710

Reputation: 37 779

2

ed, 19 characters

i
Hello World
.
w o

Sample run:

bash-4.3$ ed <<< $'i\nHello World\n.\nw o'
12

bash-4.3$ cat o
Hello World

manatwork

Posted 2016-08-01T05:37:11.710

Reputation: 17 865

2

MATL, 15 bytes

'Hello World'Z#

This creates a file called inout and writes the string to it.

Luis Mendo

Posted 2016-08-01T05:37:11.710

Reputation: 87 464

2

K, 20 Bytes

    `:f 0:,"Hello World"
    `:f

Confirmation;

    mmm@chromozorz:~/q$ cat f.txt 
    Hello World

Chromozorz

Posted 2016-08-01T05:37:11.710

Reputation: 338

Since nobody said it yet, welcome to Programming Puzzles & Code Golf. – Erik the Outgolfer – 2016-10-02T18:19:03.820

Much appreciated! – Chromozorz – 2016-10-05T19:54:02.527

OK. I also think that you have extra leading spaces though. I will edit the spaces out if you want (I don't know if they are intentionally placed, but I think it was unintentional.) – Erik the Outgolfer – 2016-10-06T05:22:08.963

2

R, 38 36 35 bytes

sink(" ");cat("Hello World");sink()

I like how the created file has no name ! It's just .txt anything, in fact !

-2 bytes thanks to @PEAR remark !
-1 bytes thanks to @BartvanNierop !

This code will produce a file with no name.

Frédéric

Posted 2016-08-01T05:37:11.710

Reputation: 2 059

1Is the '.txt' really necessary? File endings are just for the user. A single character might me enough. – PEAR – 2016-08-01T13:02:21.483

1I don't know R, but could you not shave off another byte, as by @PEAR's suggestion, by simply naming the file "a"? – Bart van Nierop – 2016-08-03T05:35:29.603

2

C#, 93 77 76 bytes

using System.IO;namespace N{class C{static void M(){File.WriteAllText("f", "Hello World");}}}

class C{static void Main(){System.IO.File.WriteAllText("f", "Hello World");}}

class C{static void Main(){System.IO.File.WriteAllText("f","Hello World");}}

See it work, with an exception for unauthorized file access.

Changelog

Rev2

  • Removed unnecessary namespace
  • Changed function name to Main (because otherwise it won't be detected as main function)
  • Removed using directive (thanks Jean Lourenço)

Rev3

  • Removed space that sneaked in.

C# (without boilerplate), 47 bytes

void M(){File.WriteAllText("f","Hello World");}

Bart van Nierop

Posted 2016-08-01T05:37:11.710

Reputation: 131

You can save some bytes by removing the using and appending it directly to the method: System.IO.File.WriteAllText[...] – Jean Lourenço – 2016-08-02T11:26:28.127

@JeanLourenço Thanks. I had that originally and then changed it for reasons unknown. – Bart van Nierop – 2016-08-02T14:15:11.067

2

Clojure, 23 bytes

#(spit"x""Hello World")

Anonymous function which creates file called x and writes Hello World there.

cliffroot

Posted 2016-08-01T05:37:11.710

Reputation: 1 080

2

Node.js, 42 bytes

require("fs").writeFile('o','Hello World')

i don't think this needs explanation

Node.js REPL, 31 bytes

fs.writeFile('o','Hello World')

for some reason in repl you dont need to include fs

Downgoat

Posted 2016-08-01T05:37:11.710

Reputation: 27 116

I don't think this works. In order for it to work, you'd need require("fs").writeFile("o","Hello World"). Otherwise, fs is not included. – Conor O'Brien – 2016-08-01T19:45:37.730

@CᴏɴᴏʀO'Bʀɪᴇɴ huh ok. works in REPL for some reason – Downgoat – 2016-08-01T19:49:05.463

2

Bash, 18 bytes

echo Hello World>a

vikarjramun

Posted 2016-08-01T05:37:11.710

Reputation: 794

1

Tcl, 28 bytes

puts [open T w] Hello\ World

sergiol

Posted 2016-08-01T05:37:11.710

Reputation: 3 055

1

Python, 34 bytes

open("h","w").write("Hello World")

Outputs to a file called h.

Leaky Nun

Posted 2016-08-01T05:37:11.710

Reputation: 45 011

1

APLX, 15 bytes

'Hello World'⍈1

Creates an APL component file containing just one component; the desired string. It can be read back with:

      'Hello World'⍇1
Hello World

Adám

Posted 2016-08-01T05:37:11.710

Reputation: 37 779

1

Gema, 28 characters

\A=@write{o;Hello World}@end

Sample run:

bash-4.3$ gema '\A=@write{o;Hello World}@end'

bash-4.3$ cat o
Hello World

manatwork

Posted 2016-08-01T05:37:11.710

Reputation: 17 865

1

Java 7, 100 95 bytes

void f()throws Exception{java.io.Writer p=new java.io.PrintWriter("x");p.print("Hello World");}

Or if you want to close the writer after using it (101 bytes):

void f()throws Exception{try(java.io.Writer p=new java.io.PrintWriter("x")){p.print("Hello World");}}

Ungolfed:

class Main{
  static void f() throws Exception{
    try(java.io.Writer p = new java.io.PrintWriter("x")){
      p.print("Hello World");
    }
  }

  public static void main(String[] a){
    try{
      f();
    } catch(Exception ex){
    }
  }
}

Usage:

java -jar Main.jar

Kevin Cruijssen

Posted 2016-08-01T05:37:11.710

Reputation: 67 575

Java is my favorite language but jesus christ it's hilarious how bad a golfing language it is haha – Shaun Wild – 2016-08-01T11:44:23.860

4@AlanTuning Indeed. xD I work with Java at work, and it's fun to code-golf in Java. You will NEVER be able to win a code-golf challenge here using Java, but it's still fun to write the Java code as short as possible. – Kevin Cruijssen – 2016-08-01T12:02:13.957

2well, you can just void f()throws Exception{new java.io.PrintWriter("x").print("Hello World");} – cliffroot – 2016-08-01T15:13:04.947

java.io.Writer p=new java.io.PrintWriter saves you some more characters. – Frozn – 2016-08-01T18:39:36.343

@cliffroot Hmm, I tried that initially, but it didn't seem to write anything to disk. Will try again tomorrow, currently I don't have an IDE and file I/O doesn't work in ideone. – Kevin Cruijssen – 2016-08-01T19:26:55.040

@Kevin Cruijssen, it seems like if you do not close the stream the write operation is not guaranteed to take place anyway. – cliffroot – 2016-08-01T20:33:55.743

1

Racket, 43 bytes

(display"Hello World"(open-output-file"f"))

Winny

Posted 2016-08-01T05:37:11.710

Reputation: 1 120

1

C#, 118 112 98 bytes


Golfed

void M(){var f=new FileInfo("_");var s=f.CreateText();s.Write("Hello World");s.Flush();s.Close();}

Ungolfed

public void M() {
    var f = new FileInfo( "_" );
    var s = f.CreateText();

    s.Write( "Hello World" );
    s.Flush();
    s.Close();
}

Full explicit code

using System.IO;

namespace N {
    class C {
        public void M() {
            // A file name is required
            FileInfo f = new FileInfo( "_" );

            // Obtain the Stream to later write on it
            StreamWriter s = f.CreateText();

            // Write 'Hello World' to the Stream
            s.Write( "Hello World" );

            // Flush it to the file
            s.Flush();

            // Close the Stream, for security and integrity reasons.
            s.Close();
        }
    }
}

Releases

  • v1.2 - -14 bytes - Changed to vars. Shoutout to Jean Lourenço.
  • v1.1 -  -6 bytes - Simplified names.
  • v1.0 - 118 bytes - Initial solution.



I'll leave a version down below that only uses the Console to write on th file. Just because I can.


C# Console Version, 39 bytes


Golfed

void M(){Console.Write("Hello World");}

Ungolfed

public void M() {
    Console.Write("Hello World");
}

Full code

using System;

namespace N {
    class C {
        public void M() {
            // Write 'Hello World' to the output handler
            Console.Write("Hello World");
        }
    }
}

Usage

<Exe. file name>.exe > FileToOutput.txt

Releases

  • v1.0 - 39 bytes - Initial solution.

auhmaan

Posted 2016-08-01T05:37:11.710

Reputation: 906

You can use 'var' instead of FileInfo and StreamWriter to save some bytes – Jean Lourenço – 2016-08-02T16:37:17.790

Right! Completely forgot the vars thing... Thanks @JeanLourenço – auhmaan – 2016-08-02T16:56:21.887

1

Julia, 47 bytes

f=open("o","w");write(f,"Hello World");close(f)

I tried using writedlm, but it didn't work out.

Mama Fun Roll

Posted 2016-08-01T05:37:11.710

Reputation: 7 234

1

C, 37 bytes

main(){system("echo Hello World>o");}

homersimpson

Posted 2016-08-01T05:37:11.710

Reputation: 281

1

Perl 6,  27  23 bytes

'o'.IO.spurt: 'Hello World'
spurt 'o','Hello World'

Brad Gilbert b2gills

Posted 2016-08-01T05:37:11.710

Reputation: 12 713

1

eacal, 26 bytes

write a string Hello World

This writes a string Hello World to file a, creating it if not present. Basically:

write <fileName> <exec>

and

string <params to convert to string>

Run the program as:

λ node eacal.js writeFile

Conor O'Brien

Posted 2016-08-01T05:37:11.710

Reputation: 36 228

1

J, 21 bytes

'Hello World'1!:3<'o'

This writes to a file o in the current directory, or, if not called from a file, in your j64-804 file. 1!:3 is the write foreign, and <'o' is the boxed filename (filenames need to be boxed). The LHS is the string to write.

Conor O'Brien

Posted 2016-08-01T05:37:11.710

Reputation: 36 228

1

Java

public class H
{
    public static void main(String[] a)
        throws IOException
    {
        FileWriter o = new FileWriter("x");
        o.write("Hello World");
        o.close();
    }
}

Simple I/O with no exception handling.

Corrected

Corrected the original code to write the correct string (Hello World).

David R Tribble

Posted 2016-08-01T05:37:11.710

Reputation: 115

2Your answer would have been shorter if you had actually wrote the correct string.. – Shaun Wild – 2016-08-02T09:11:52.430

@SeanBean: Huh, force of habit, I guess, that I wrote Hello, world. I corrected the code. – David R Tribble – 2016-08-04T23:07:48.220

@DavidRTribble You can change public class H to class H and IOException to Exception. This will save you 9 bytes. Also, you should include the import java.io.*; – Bashful Beluga – 2016-08-05T15:12:09.297

1

JavaScript, 89 bytes

This code was tested in Chrome. In other browsers, the element must be in the document for the click method to work.

a=document.createElement("a");a.href="data:text/plain,Hello World";a.download=1;a.click()

kamoroso94

Posted 2016-08-01T05:37:11.710

Reputation: 739

1

HTML, 83 bytes

This code was tested in Chrome. It relies on the image failing to load, then it clicks itself, triggering the anchor tag which is a download link.

<a href="data:text/plain,Hello World" download><img src onerror="this.click()"></a>

kamoroso94

Posted 2016-08-01T05:37:11.710

Reputation: 739

0

QBasic, 39 bytes

OPEN"f"FOR OUTPUT AS#1
?#1,"Hello World

Opens a file named f (creating it if it doesn't exist, wiping it if it does) and gives it the file handle #1. Then prints (?) to file #1 the string Hello World (with a trailing newline).

DLosc

Posted 2016-08-01T05:37:11.710

Reputation: 21 213

0

Bash script, 20 18 bytes

echo Hello World>o

Save this as a file write.sh and run it: `bash o.sh

dkudriavtsev

Posted 2016-08-01T05:37:11.710

Reputation: 5 781

5Why did you repost a deleted answer? – Dennis – 2016-08-01T06:17:07.590

2Surely the quotes are unnecessary? – Neil – 2016-08-01T09:19:15.117

1You can save a byte by escaping the space instead of using quotes: Hello\ World – MTCoster – 2016-08-01T14:13:33.130

@MTCoster, why? help echo says: “Display the ARGs, separated by a single space character and followed by a newline, on the standard output.” – manatwork – 2016-08-01T16:52:37.663

@manatwork You're absolutely right, I was unaware of this! – MTCoster – 2016-08-01T16:53:52.263

@Dennis It was downvoted due to rules being written incorrectly. The rules are now fixed and I wanted to repost that answer without the downvotes. – dkudriavtsev – 2016-08-03T23:47:07.550

That's not a good reason. After the rules have been clarified, people can just retract their downvotes. Duplicate answers are automatically flagged for moderator attention. Also, your edit makes your answer identical to this one.

– Dennis – 2016-08-03T23:54:49.793

0

AutoIT, 43 40 bytes

FileWrite(FileOpen("a",1),"Hello World")


Explanation

FileOpen takes two parameters and returns the handle of the file. Mode must be 1 for writing (appending) text.

FileOpen ( "filename" [, mode = 0] )

FileWrite takes two parameters, a handle and the text to write

FileWrite ( "filehandle/filename", "text/data" )

If a file does not exist, AutoIT will create it. Note that in my example it will not have any file extension associated (filename: a), but can still be opened with any text editor.

AutoIT is a Windows only scripting language.

Script-Example.com has an online AutoIT compiler that can verify the solution.

Daniel

Posted 2016-08-01T05:37:11.710

Reputation: 1 808

0

Php, 38 bytes

file_put_contents('a', 'Hello World');

Michael Kunst

Posted 2016-08-01T05:37:11.710

Reputation: 513

1

You can save 15 bytes by calling the execution operator. \echo Hello\ World > a``

– ʰᵈˑ – 2016-08-01T13:26:23.887

2Heh heh that's not really PHP anymore. – Alex Howansky – 2016-08-01T16:24:14.330

136 bytes: fputs(fopen('a','c'),'Hello World'); – Alex Howansky – 2016-08-01T16:28:59.383

@AlexHowansky You can do fputs(fopen(a,c),'Hello World'); and save 4 bytes. – Ismael Miguel – 2016-08-02T13:32:19.140

0

Nim, 28 26 bytes

"o".writeFile"Hello World"

Yes, Nim has a function in the system module for opening a file, writing a string to it, then closing it again.

Copper

Posted 2016-08-01T05:37:11.710

Reputation: 3 684

0

PHP, 34 bytes

fputs(fopen(7,'c'),'Hello World');

MonkeyZeus

Posted 2016-08-01T05:37:11.710

Reputation: 461

@Lukabot I reverted your edit because it should have been a comment, and it is completely different enough to be its own answer (the same language can be used multiple times if the approach is different) – NinjaBearMonkey – 2016-08-02T02:09:06.987

0

Mathematica, 27 bytes

".txt"~Export~"Hello World"

alephalpha

Posted 2016-08-01T05:37:11.710

Reputation: 23 988

Like in the answer using R... isn't a single character enough for the file name? – PEAR – 2016-08-04T10:06:59.627

@PEAR Mathematica can't infer the file format without a file extension. – alephalpha – 2016-08-04T10:20:48.777

Oh, ok... maybe something shorter encoded in the same way?... .c for example? – PEAR – 2016-08-04T10:22:54.387

0

Perl, 20 bytes

`echo Hello World>o`

Perl will execute anything in backticks (`) as a system command.

homersimpson

Posted 2016-08-01T05:37:11.710

Reputation: 281

0

ListSharp, 37 bytes

OUTP="Hello World" HERE[<here>+"\\a"]

simply writes Hello World to a file called "a"(not even a text file) in the script execution environment,

downrep_nation

Posted 2016-08-01T05:37:11.710

Reputation: 1 152

0

PHP, 27 bytes

exec('echo Hello World>o');

PHP, 20 bytes

`echo Hello World>o`

Lukabot

Posted 2016-08-01T05:37:11.710

Reputation: 3

0

C#, 50 bytes

s=>System.IO.File.WriteAllText("f","Hello World");

An anonymous function that takes in an unused argument and outputs the file.

Alternatively and cheating slightly this one:

s=>System.IO.File.WriteAllText("f",s);

That takes in a string and works assuming the string contains the text: Hello World, for 38 bytes.

TheLethalCoder

Posted 2016-08-01T05:37:11.710

Reputation: 6 930

0

Common Lisp, 69 bytes

Lauded for being incredibly expressive, it's not the best golfing language...

(with-open-file (f "f" :direction :output) (format f "Hello, world"))

See it work, with permission denied.

Bart van Nierop

Posted 2016-08-01T05:37:11.710

Reputation: 131

0

Awk, 29 characters

BEGIN{print"Hello World">"o"}

(No, not another output redirection. Just Awk's syntax is similar.)

Sample run:

bash-4.3$ awk 'BEGIN{print"Hello World">"o"}'

bash-4.3$ cat o
Hello World

manatwork

Posted 2016-08-01T05:37:11.710

Reputation: 17 865

0

Groovy, 28 characters

new File("o")<<"Hello World"

Sample run:

bash-4.3$ groovy -e 'new File("o")<<"Hello World"'

bash-4.3$ cat o
Hello World

manatwork

Posted 2016-08-01T05:37:11.710

Reputation: 17 865

0

Sed, 20 characters

(19 characters code + 1 character dummy input.)

s/^/Hello World/
wo

Seems the side effect of also displaying the string to STDOUT after the file was created is not prohibited.

Requires dummy input to work as per Are languages like sed exempt from “no input” rules?

Sample run:

bash-4.3$ sed $'s/^/Hello World/;wo' <<< ''
Hello World

bash-4.3$ cat o
Hello World

manatwork

Posted 2016-08-01T05:37:11.710

Reputation: 17 865

0

BASH, 13 bytes

When we asume that the filename is part of the contents of a file:

>Hello\ World

CousinCocaine

Posted 2016-08-01T05:37:11.710

Reputation: 1 572