A "cheating" quine

56

6

Long-time lurker, first-time poster. So here goes.

In the Wikipedia page for quine, it says that "a quine is considered to be 'cheating' if it looks at its own source code." Your task is to make one of these "cheating quines" that reads its own source code.

This is , so the shortest code in bytes - in each language - wins. This means that a 5-byte Pyth script would not beat a 21-byte Python script - but a 15-byte Python script would.

You must use file I/O to read the source code, so the following JavaScript code, taken from the official Wikipedia page, is invalid:

function a() {
    document.write(a, "a()");
}
a()

It must access the source code of the file on disk.

You are not allowed to specify the file name. You must make it detect the filename itself.

Everyone clear? Go!

TheInitializer

Posted 2015-10-29T21:54:13.240

Reputation: 829

Is it allowed to specify the name of the file that the program is run in? How should that be scored? – isaacg – 2015-10-29T22:01:05.460

1Is a trailing newlines not present in the original file allowed? – isaacg – 2015-10-29T22:04:37.320

3@isaacg IMHO That's not a quine, since it is not the source code. – mınxomaτ – 2015-10-29T22:05:28.830

3You should state a requirement that it determine the actual filename instead of assuming a hard-coded string for the source location. – feersum – 2015-10-29T22:26:09.270

3I agree with @feersum though, that requiring a specific file name makes this challenge way to trivial. – mınxomaτ – 2015-10-29T22:33:52.320

@isaacg No, it isn't. I'll add that to the OP – TheInitializer – 2015-10-29T23:01:29.780

1Can we assume that (for compiled languages) the source code is in the same folder (i.e. we can just add ".cpp" or ".hs" to arg[0] to get the source). – HEGX64 – 2015-11-01T09:15:23.097

1@HEGX64 Sure, that makes sense. – TheInitializer – 2015-11-01T19:23:46.033

APL uses a workspace to store and execute code. May I read the program code from the workspace? The program will not contain its own name. – Adám – 2016-05-25T11:37:27.247

1@Adám I'm not sure how this workspace thing works, but what I'm going for is reading the program code from the filesystem. If it does that, great. – TheInitializer – 2016-05-25T22:35:54.287

@TheInitializer The workspace is already fully loaded into memory before the command is given to a program to run. In that sense, the workspace is APL's virtual "file" system.

– Adám – 2016-05-25T23:24:39.123

@Adám It seems fine I guess. – TheInitializer – 2016-05-26T23:07:30.083

Answers

60

Zsh, 4 bytes

<$0

The Z shell has feline functionalities built in. The fourth character is a linefeed.

Try it online!

The code does not depend in any way on the file name; it works even if the file name contains special character, such as spaces or newlines.

Test run

$ cat "my quine.sh"
<$0
$ zsh "my quine.sh" 
<$0
$ diff -s <(zsh "my quine.sh") <(cat "my quine.sh")
Files /dev/fd/63 and /dev/fd/62 are identical

Dennis

Posted 2015-10-29T21:54:13.240

Reputation: 196 637

28feline functionalities :) – theB – 2015-10-31T10:51:55.540

48

Bash, 6 bytes

cat $0

Basically.

a spaghetto

Posted 2015-10-29T21:54:13.240

Reputation: 10 647

1Why was this down voted? It does exactly what the program asked for. – Addison Crump – 2015-10-29T22:03:15.057

1Doesn't cat append a trailing newline? So this is 7 bytes? – isaacg – 2015-10-29T22:03:22.180

3It does not print a newline. – Addison Crump – 2015-10-29T22:06:02.910

2cat does not append a newline (at least on my system). – a spaghetto – 2015-10-29T22:06:25.640

7@isaacg cat prints the content of the supplied file byte per byte. – Dennis – 2015-10-29T22:17:36.350

1Note that #!cat in a file also works for a cheating quine. But not when the file is called with bash. – LukStorms – 2015-10-29T22:47:52.670

@LukStorms That's a good point. I wonder if that is valid... – a spaghetto – 2015-10-29T22:53:41.020

Not sure. It does feel like a bigger cheat. – LukStorms – 2015-10-29T22:56:23.817

@LukStorms it would mean that I could beat Pyth though (mwahahaha). I'll ask chat what they think – a spaghetto – 2015-10-29T22:56:54.873

2@LukStorms But wouldn't this be a cat solution then, instead of a bash solution? And cat does not really qualify as programming language – Fabian Schmengler – 2015-10-29T23:07:13.237

@fschmengler I'd say it's a sh solution, and cat is just one of many possible standard system commands in a sh shebang. – Sparr – 2015-10-29T23:25:17.710

@Sparr: On my system, #! works even if sh doesn't exist (but you have to use the full path). – Joshua – 2015-10-29T23:35:57.913

@Joshua sure, because #! also exists in whatever shell you're using to run the script. It's not just a sh directive. – Sparr – 2015-10-29T23:45:10.837

@Sparr: I discovered it's in the kernel on my system. – Joshua – 2015-10-30T01:17:32.950

30Will this work if the file is named -e ? – Mark Plotnick – 2015-10-30T06:05:24.700

1@fschmengler & Joshua. Now that I readup on the shebang. It seems when it's in a script on a unix-like system it's called by the program loader of the system. So if you run a script with only a she-banged line then you can't call it a bash script. – LukStorms – 2015-10-30T08:37:08.787

@MarkPlotnick I have no idea how you would run a shell script named this from the command line. You can't escape the dash with a backslash. – a spaghetto – 2015-10-30T18:06:39.147

1If the file name starts with a dash, you'd have to call the script as bash ./-e, which will still work, since this is the argument that gets passed to Bash. (Without quotes, $0 won't handles whitespace in the file name though.) – Dennis – 2015-10-30T18:11:34.733

@LukStorms #!cat only works if your current directory is /bin. I wonder whether a solution is allowed to make such requirements. – kasperd – 2015-10-31T21:58:37.203

@MarkPlotnick If the file is named -e and executed like this execl("-e", "-e", NULL);, then bash will in fact think -e is an option rather than a file name. But if the script is invoked from a bash shell, I am not sure you can get bash to invoke the script without passing a path to the file. – kasperd – 2015-10-31T22:10:58.797

@kasperd Also depends on your $PATH variable? PATH normally has /usr/bin, which includes cat. – LukStorms – 2015-10-31T22:30:38.863

@LukStorms Scanning the PATH is done by user mode library code, but #! is handled by the kernel and doesn't take PATH into account. If you want a #! line to use PATH it is usually done by taking advantage of an intermediate program like for example #!/usr/bin/env python, but that's not very useful for code golf. – kasperd – 2015-10-31T22:35:21.453

@kasperd Ok. I had only tested it in cygwin, which doesn't have a problem with it. But on a linux it's indeed a problem. Not that it matters, it was already discussed that it wouldn't count as a bash script. – LukStorms – 2015-10-31T23:18:47.750

@MarkPlotnick Naming the file "-e" works fine on bash, zsh and sh for me. – Desty – 2015-11-02T11:08:53.063

Not pure bash, it needs some other executable, namely cat, present and findable in the $PATH. However, bash does the interpretation logic, and if cat is present, it can be assumed as a command available to bash. – Golar Ramblar – 2017-05-12T20:19:01.960

@GolarRamblar Most bash submissions assume coreutils are available. – a spaghetto – 2017-05-12T20:25:56.133

32

UNIX executable loader, 10 bytes

#!/bin/cat

If you don't care about spam on standard error, you can make it one byte shorter:

#!/bin/dd

Joshua

Posted 2015-10-29T21:54:13.240

Reputation: 3 043

7I like this. Not sure if it qualifies as a "language," though. – Kevin – 2015-10-29T23:39:09.320

Perhaps cheating a bit, but couldn't you rename your bin folder and the cat program to shorten the path? – James Webster – 2015-10-30T09:54:22.710

3I'm not suggesting you do btw. I'm suggesting you could – James Webster – 2015-10-30T09:54:53.637

3@Kevin The "language" (that is, interpreter) is cat. And I guess if you want to be very specific, a cat program simply prints itself, and is compatible with every file format in existence :) – l0b0 – 2015-10-30T10:38:10.447

1@JamesWebster sudo install /bin/cat /c. Y'know, just in case /bin isn't on the root filesystem. Gotta have that cat in singleuser… – Blacklight Shining – 2015-10-30T23:08:34.253

@l0b0: The "language" here is not cat. The interpreter we play with here is within the kernel (e.g., Linux), which reads the first two bytes (magic bytes) of a file given to it in order to execute it, and if it finds them to be #!, it continues to read the line to get a path of another executable which it will then execute, passing the file's path as an argument to it. The interpreter here is not cat, but part of the kernel. cat is just invoked after the kernel interpreted the first line, and then just does the file I/O. Here it is the same as with the bash-answer (cat $0) above. – Golar Ramblar – 2017-05-12T20:14:01.127

25

C, 52

s[99];main(){read(open(__FILE__,0),s,99);printf(s);}

Of course, this reads the source code and not the compiled program - I assume that's within spec.

Digital Trauma

Posted 2015-10-29T21:54:13.240

Reputation: 64 644

You could use printf instead of puts to avoid a trailing newline. – feersum – 2015-10-29T22:51:50.420

@feersum yes, good catch – Digital Trauma – 2015-10-29T22:52:58.387

@downvoter ... you know ... just curious... – Digital Trauma – 2015-10-30T04:15:34.533

19@DigitalTrauma It's because of your avatar, of course – Peter Olson – 2015-10-30T06:27:54.837

3Actually, puts can be used, you just need to read fewer characters. – user4098326 – 2015-10-31T01:41:47.580

You are assuming s is initialized with NUL characters. Is that guaranteed to be the case? – kasperd – 2015-10-31T23:24:21.923

2

@kasperd Yes, guaranteed by C89

– Digital Trauma – 2015-11-01T00:06:17.297

Save two bytes: s[50];main(){read(open(__FILE__,0),s,50);puts(s);} by reading only 50 characters you skip the possible newline and can use puts instead of printf. – MD XF – 2017-05-24T03:04:50.653

If you don't want to edit that in, can I post it as a new answer? – MD XF – 2017-05-24T03:10:12.557

@MDXF Normally such a trivial difference doesn't warrant a new answer, so I wouldn't encourage it. I can't stop you though ;-). FWIW, if you use puts() then the extra newline will mean your source must also end in a newline, making it 51 bytes. – Digital Trauma – 2017-05-24T03:52:36.643

@DigitalTrauma Still a byte less... :D – MD XF – 2017-05-24T03:53:00.087

13

PHP, 21 Bytes

<?=file(__FILE__)[0];

file reads a file line by line into an array and the file only has one line. This saves a byte in comparison to readfile(__FILE__).

Fabian Schmengler

Posted 2015-10-29T21:54:13.240

Reputation: 1 972

Notice that this only works from PHP5.4 and up, which was the first version to support array de-referentiation. But other than that, quite a nice answer! – Ismael Miguel – 2015-11-03T09:19:34.090

1readfile is also 21: <?readfile(__FILE__);. – primo – 2015-11-03T15:42:24.907

1Right, it doesn't need <?= – Fabian Schmengler – 2015-11-03T15:55:53.297

12

Perl, 15 bytes

open 0;print<0>

Saved 3 bytes thanks to @ThisSuitIsBlackNot!

Dom Hastings

Posted 2015-10-29T21:54:13.240

Reputation: 16 415

2You can save 3 bytes with open 0;print<0> – ThisSuitIsBlackNot – 2015-11-02T03:45:08.860

@ThisSuitIsBlackNot I was sure there was a shorter way to do it, but I couldn't for the life of my work it out... Using 0 assumes $0 then? – Dom Hastings – 2015-11-02T05:44:18.810

3Yep. See perldoc -f open: "As a shortcut a one-argument call takes the filename from the global scalar variable of the same name as the filehandle: $ARTICLE = 100; open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";" – ThisSuitIsBlackNot – 2015-11-02T06:41:15.690

11

Python 2, 32 bytes

There's a newline at the end of the file.

print open(__file__).readline()

Python 3, 33 bytes

There's a newline at the end of the file.

print(open(__file__).readline())

Thanks to feersum for catching a problem and supplying __file__, Loovjo for a new approach to the Python 2 solution that saved 17 bytes, and Skyler for a solution that saved yet another byte and worked in both Python 2 and 3 (pending print being a function in Python 3)!

Doc link for readline

Celeo

Posted 2015-10-29T21:54:13.240

Reputation: 520

This would also save 2 bytes in python3 because you could discard the end parameter. – Skyler – 2015-11-02T21:24:21.790

@Skyler You're absolutely correct. – Celeo – 2015-11-02T21:34:22.350

How does this work in Python 3, which needs parens for print? – Doorknob – 2015-11-02T21:36:30.153

Python 3 should be print(open(__file__).readline()) followed by a newline. – Skyler – 2015-11-02T21:37:44.017

Your Python 3 example says Python 2 rather than Python 3 – TheInitializer – 2016-05-25T22:39:12.660

@TheInitializer fixed, thanks – Celeo – 2016-05-25T22:47:11.620

11

osascript (AppleScript from the command line), 40 33 32 bytes

(read path to me)'s paragraph 1

Executing on a file called a with osascript a.

Gets the first paragraph (line) of the file and prints it to STDOUT with a trailing newline, therefore the newline in the code.

Addison Crump

Posted 2015-10-29T21:54:13.240

Reputation: 10 763

1See my edit to the OP – TheInitializer – 2015-10-29T23:03:59.570

Working on getting it to work. – Addison Crump – 2015-10-29T23:07:07.777

read path to me seems to work for me. El Cap. – Digital Trauma – 2015-10-29T23:15:39.130

Didn't see this, but this is the way I ended up doing it. :P Thanks, @DigitalTrauma. EDIT: trailing newlines must be considered, so you add the newline and use paragraphs 1. – Addison Crump – 2015-10-30T07:30:59.757

11

Perl 6, 20 bytes

print slurp $?FILE

I haven't worked with Perl 6 very long so I'm not sure if there are any tricks to make this shorter.

Hotkeys

Posted 2015-10-29T21:54:13.240

Reputation: 1 015

2can you remove the second space? – Eevee – 2015-11-01T02:03:17.177

3@Eevee nope, it gets angry – Hotkeys – 2015-11-01T09:25:44.523

10

Python 2.7, 30 bytes

print open(__file__).read(29)

Edit: Just to be clear, the code above is supposed to have a newline at the end as the 30th byte. I'm not familiar with markdown enough to figure out how to display it in the code block.

I'm using the same trick here as the one in my C submission. This reads the whole source file excluding the trailing newline to account for the additional newline which print will append to the output.

xsot

Posted 2015-10-29T21:54:13.240

Reputation: 5 069

Does this run into the same problem with the trailing newline that the other submission did? – cole – 2015-10-30T00:21:48.567

No. There's supposed to be a trailing newline that makes the 30th byte in the source code but I can't get it to display in the code block. My submission works because it reads the first 29 bytes of the source code so that the newline from print won't be extraneous. – xsot – 2015-10-30T00:25:52.887

4That's not what the comma does. It appends a space instead of a newline. – xsot – 2015-10-30T01:00:42.320

2could use to indicate a semantically-important newline – Eevee – 2015-11-01T02:02:23.543

10

Batch, 9 8 Bytes

@type %0

Saved a byte thanks to @Joshua

Fabian Schmengler

Posted 2015-10-29T21:54:13.240

Reputation: 1 972

3You can save a byte by eliminating the trailing %. – Joshua – 2015-10-30T04:02:39.633

9

Java, 212 196 Bytes (171 Bytes with questionable hard-coding rules)

Thanks to @Cruncher for shortening it by ~15 bytes!

I have no doubt this can be golfed.

import java.nio.file.*;class A{public static void main(String[]a){new A();}A(){try{System.out.print(new String(Files.readAllBytes(Paths.get(getClass().getName()+".java"))));}catch(Exception e){}}}

Or, another method, using the static method (and the name of the class), I get 171 bytes. I'm not sure if this qualifies as hard-coded, though.

import java.nio.file.*;class A{public static void main(String[]a)throws Exception{System.out.print(new String(Files.readAllBytes(Paths.get(A.class.getName()+".java"))));}}

Uses a constructor to get the class name by a non-static method. Using a static method (A.class.getName()) was really hard coded, so I used the 'proper' way. Using A.class.getName(), this code shortens down to 171 bytes.

Readable versions:

Using constructor and this.getClass():

import java.nio.file.*;
class A{
    public static void main(String[]a) {
        new A();
    }
    A(){
        try{
            System.out.print(
                new String(
                Files.readAllBytes(
                Paths.get(
                getClass().getName()+".java"))));
        }
        catch(Exception e) {}
    }
}

Using static method A.class.getName():

import java.nio.file.*;
class A {
    public static void main(String[] a) throws Exception {
        System.out.print(
             new String(
                  Files.readAllBytes(
                       Paths.get(
                            A.class.getName()+".java"))));
    }
}

Grabs all the bytes of the file at once and outputs it to STDOUT. Pretty straightforward.

Addison Crump

Posted 2015-10-29T21:54:13.240

Reputation: 10 763

Why just not use A.class.getName()? – Fabio F. – 2015-10-30T08:18:26.593

@FabioF. I felt that that was too hard coded - I did add that as a note in my answer. – Addison Crump – 2015-10-30T08:19:46.310

3It's CodeGolf not CodeReview! ;) – Fabio F. – 2015-10-30T08:26:43.363

@FabioF. Added both answers. :P – Addison Crump – 2015-10-30T08:34:05.170

1@FabioF. Yeah, but I think that dances on the line of being a hardcoded filename, which is against the rules. The point is, if you change the name of the file, you have to change the name of the class (obviously), but also change this line, which is like a hardcoded filename. – Cruncher – 2015-10-30T17:39:43.420

1Can't you call the print statement inside the constructor and save yourself from setting a static variable? – Cruncher – 2015-10-30T17:45:40.947

@Cruncher You're absolutely right, thanks! – Addison Crump – 2015-10-30T17:48:03.997

Actually, @Cruncher, I remember why I didn't do that - I would throw an IOException. Keeping it in the main method allows me to keep it down to one throws statement / no try/catch. – Addison Crump – 2015-10-30T17:53:06.137

@VoteToClose just need main and the constructor to "throws Exception". The following code is 208 bytes: import java.nio.file.*;class A{public static void main(String[]a)throws Exception{new A();}A()throws Exception{System.out.print(new String(Files.readAllBytes(Paths.get(this.getClass().getName()+".java"))));}} – Cruncher – 2015-10-30T17:54:08.517

It also appears like you can remove the "this." in front of getClass to make it 203 – Cruncher – 2015-10-30T17:56:40.713

That's great! I used a try/catch in the constructor instead, that shortens it further. – Addison Crump – 2015-10-30T17:59:17.613

Oh right. Throws is shorter than try/catch, but try/catch is shorter than 2 throws – Cruncher – 2015-10-30T18:00:06.870

My name isn't Crusher btw :) – Cruncher – 2015-10-30T18:04:44.620

Whoops! I knew it had something to do with smooshing! Fixed. – Addison Crump – 2015-10-30T18:05:42.387

It actually looks like the method of reading the file in my answer is shorter. It's 4 characters longer, but the import is 6 characters shorter. That should get you down to 195 if you use that. Or maybe I'll take the method of getting the class name. IDK – Cruncher – 2015-10-30T18:13:33.060

1@Cruncher Nah. You get java.io, I'll stick to java.nio - the point is not to win, but show ways to do it extremely concisely with different methods. – Addison Crump – 2015-10-30T18:14:50.087

Neat! I stole some of your ideas for the C# answer. – Brian Reischl – 2015-10-30T18:49:18.527

8

AutoIt, 34 bytes

Outputs itself to the clipboard:

ClipPut(FileRead(@ScriptFullPath))

mınxomaτ

Posted 2015-10-29T21:54:13.240

Reputation: 7 398

8

Ruby, 14

$>.<<IO.read$0

histocrat

Posted 2015-10-29T21:54:13.240

Reputation: 20 600

Nice use of . to avoid parentheses – Cyoce – 2017-07-03T06:21:51.610

7

PowerShell, 39 36 31 25 Bytes

About as tight as I can get it:

gc $MyInvocation.MyCommand.Path | oh

Backed by popular demand this has been changed to:

gc $PSCommandPath|echo -n

prints to host shell current standard output.

Chad Baxter

Posted 2015-10-29T21:54:13.240

Reputation: 248

gc $MyInvocation.MyCommand.Path is enough. It will automatically print it out. – Andrew – 2015-10-30T00:44:22.363

its not guaranteed to especially if the script is running silently – Chad Baxter – 2015-10-30T00:49:33.680

Haha yea I don't care. I was going to post if no one else had a PowerShell answer. But I forgot that gc was an alias and was just going to use cat, so you had a byte on me there anyway. – Andrew – 2015-10-30T00:51:51.017

Uh, I wouldn't be that strict about it. Otherwise every PS answer would explicitly have to pipe to the host shell, but that's up to you... – Andrew – 2015-10-30T00:57:40.920

You could instead use gc $PSCommandPath for 17 bytes. The problem I see is that this spits out a newline (which doesn't exist in the source). It's ambiguous now if trailing newline is OK or not ... depending upon how that rules, we may need to do something tricksy like gc $PSCommandPath|write-host -n for 31 bytes. – AdmBorkBork – 2015-10-30T13:03:30.817

Also, welcome to PPCG! – AdmBorkBork – 2015-10-30T13:05:42.807

hahaha yes not sure on the ruling on that, hopefully OP will answer that...thanks team! – Chad Baxter – 2015-10-30T20:41:20.597

7

Go, 111 105 bytes

package main
import("io"
."os"
."runtime")
func main(){_,p,_,_:=Caller(0)
f,_:=Open(p)
io.Copy(Stdout,f)}

My first code-golf in Go – just a few tricks you can use here I guess.

tomasz

Posted 2015-10-29T21:54:13.240

Reputation: 281

There is already an answer in Go - does this use the same method? – Addison Crump – 2015-10-30T12:20:21.490

@VoteToClose: I realise it, I was inspired by the other one indeed, but used package renaming here (cheap trick) as well as different technique for opening and piping file to stdout. Saved me a massive 22 bytes ;-) – tomasz – 2015-10-30T12:36:43.247

The method is actually a bit different, good one! – Fabian Schmengler – 2015-10-30T13:27:51.153

5

Peter Lenkefi

Posted 2015-10-29T21:54:13.240

Reputation: 1 577

11I've converted this to a community wiki because it isn't your own work. – Alex A. – 2015-10-29T23:58:49.167

5

C, 49 bytes

s[];main(){read(open(__FILE__,0),s,48);puts(s);}

Edit: To clarify, the 49th byte is a newline.

This reads the source code minus the newline at the end to account for the newline which puts will append to the end of the output.

xsot

Posted 2015-10-29T21:54:13.240

Reputation: 5 069

This code invokes undefined behavior twice. – Joshua – 2015-10-30T04:03:40.960

5Well, this is code golf. My code produces the desired output so it's a valid submission. – xsot – 2015-10-30T04:16:35.157

1@xsot In that case, you should probably list the compiler version + options; otherwise this might not be verifiable. – Justin – 2015-10-30T07:16:05.623

It should work for most versions of gcc without any compilation option. – xsot – 2015-10-30T07:29:42.553

You'll also have to specify the filesystem it's on in this case. Some filesystems may not ensure the first read() call returns all 48 bytes (a successful read will read between 1 byte and the number of bytes passed). – Joshua – 2015-10-30T15:31:23.337

1If having undefined behavior is permitted as long as you can have some compiler that produces the desired output on some machine during some phase of the moon, then I propose int main(void) { *0; } as a solution. After all, the standard would permit an implementation that compiles that into a program that solves the problem. I'd be fine with using implementation-dependent behavior as long as you specify the compiler, but with undefined behavior, you can't even guarantee that you wouldn't get ten different answers if you ran that ten times in a row on the same machine. – Ray – 2015-11-03T00:44:26.380

@Ray Sure, you could write a compiler that makes int main(void) { *0; } as a solution, but 1 you'd have to mark solutions using it as noncompeting 'cause it'd be newer than the challenge; 2 you'd be downvoted into oblivion; 3 it's really boring. – MD XF – 2017-05-30T21:15:18.620

1@MDXF I wasn't seriously suggesting that we write that solution. I was arguing against allowing undefined behavior. int main() {*0;} might work even on existing compilers, since it contains undefined behavior. Similarly, xsot's solution might work on existing compilers, since it contains undefined behavior. Neither one is guaranteed to solve the problem. (Although xsot's is admittedly more likely to do so, it might just as easily crash). My actual argument is that we should permit solutions that depend on implementation-dependent or unspecified behavior, but not undefined behavior. – Ray – 2017-05-31T19:43:53.453

@Ray So it would've been better practice if he'd included in the header (gcc) or (clang) or (tcc), but the truth is, most smart compilers these days will perform the same for some types of undefined behavior. This is one. – MD XF – 2017-05-31T19:45:28.210

@MDXF That would be useful if it was implementation-dependent or unspecified behavior. But if it's undefined, it might work one run and crash the next, even with the same compiler. He's writing to an array with no memory allocated to it. This isn't a purely theoretical situation; that might very well crash depending on what lives in that memory. (Though the fact that it's declared in file scope makes it a bit less likely.) – Ray – 2017-05-31T19:49:01.850

5

Mathematica, 16 bytes

FilePrint@$Input

Run it in script mode.

alephalpha

Posted 2015-10-29T21:54:13.240

Reputation: 23 988

I've been using Mathematica for many years and had never even heard of script mode. – Michael Stern – 2015-11-13T18:04:24.123

4

Pyth, 25 bytes

$import sys$h'e$sys.argv

This reads its file name. Essentially, it looks up argv, opens the file corresponding to its last argument, and prints its first line.

isaacg

Posted 2015-10-29T21:54:13.240

Reputation: 39 268

Can't you just do h'$__file__$? – kirbyfan64sos – 2015-10-29T23:34:47.167

@kirbyfan64sos That gives me the error NameError: name '__file__' is not defined. Pyth is compiled to Python, and then the resultant string is executed. So I wouldn't expect that to work. – isaacg – 2015-10-29T23:41:09.633

4

Go, 133 Bytes

Everyone clear? Go!

package main
import("fmt"
"io/ioutil"
"runtime")
func main(){_,f,_,_:=runtime.Caller(0)
s,_:=ioutil.ReadFile(f)
fmt.Print(string(s))}

Fabian Schmengler

Posted 2015-10-29T21:54:13.240

Reputation: 1 972

2This inspired me to write my own (and the very first) code-golf solution in Go. Looking for some general tricks, you can easily go down to 123 characters here by applying single-letter names for packages, for example r"runtime". – tomasz – 2015-10-30T12:27:13.460

4

><>, 31 bytes

Disclaimer : there is no file I/O in ><>, however I thought it would be interesting to showcase its codespace I/O inherited from Befunge, one of the language that inspired ><>.

00voa0+1;!?$~<
1+> :r:@g: ?!^o$

A self-reading Quine I made some time ago, you can try it here.

I just saw there is a shorter ><> self-reading quine. While it is clearly better in code-golf standards I'd like to point out it has hardcoded code length, while mine would copy additionnal lines or columns of code (as long as they don't break the original code).

Aaron

Posted 2015-10-29T21:54:13.240

Reputation: 3 689

I was thinking of posting in ><>, but I thought ><> would be impossible due to the rule: "You must use file I/O to read the source code" – Sp3000 – 2015-11-03T11:47:52.027

@Sp3000 woops indeed, looks like I didn't read the challenge well enough. I'll add a disclaimer – Aaron – 2015-11-03T12:00:17.887

4

><>, 13 Bytes

0:0go:c=?;1+!

Tested both on the online and offline interpreters. The g command is the closest to being able to read from the source file and if it doesn't count for the purpose of this challenge I'll mark my entry non-competing; I do believe it normally considered "cheating" for quines.

Try it online.

cole

Posted 2015-10-29T21:54:13.240

Reputation: 3 526

4

Haskell, 63 bytes

For science!

import System.Environment
main=getProgName>>=readFile>>=putStr

Craig Roy

Posted 2015-10-29T21:54:13.240

Reputation: 790

Only works with the runhaskell command. Very cool though – HEGX64 – 2015-11-02T22:44:17.227

3

Haskell, 49 bytes

{-#LANGUAGE CPP#-}main=putStr=<<readFile __FILE__

Try it online!

(GHC) Haskell has an extension to use the C preprocessor (commonly used for portability between versions and architectures.) Hopefully self-explanatory.

Ørjan Johansen

Posted 2015-10-29T21:54:13.240

Reputation: 6 914

3

HTML with JavaScript, 115 bytes (doesn't really count)

<!DOCTYPE html><html><title>x</title><script>alert(new XMLSerializer().serializeToString(document))</script></html>

Does this count? I don't mind, it was fun :)

Technically it doesn't open a file. It's also a well-formed HTML5 document. The XMLSerializer was the only tool which also returned the DOCTYPE portion, but is non-standard. Still, it works on chrome and firefox, and I bet other browsers.

And as a bonus:

JavaScript, 41 bytes

alert(document.currentScript.textContent)

Domino

Posted 2015-10-29T21:54:13.240

Reputation: 459

Remove ";" at the end, save 1 byte :) – Евгений Новиков – 2017-07-03T07:44:48.420

1@ЕвгенийНовиков You're right, not sure why I left that in back then. It seems like I didn't count it though. – Domino – 2017-07-04T11:07:48.750

3

F#, 54 Bytes

printf"%s"(System.IO.File.ReadAllText __SOURCE_FILE__)

Usage:

fsi --exec a.fsx

p.s.w.g

Posted 2015-10-29T21:54:13.240

Reputation: 573

3

Perl 5, 15 13 bytes

Credit to the Bash solution for inspiring this:

print`cat $0`

EDIT: Don't need the semi-colon or first space.

Erikster

Posted 2015-10-29T21:54:13.240

Reputation: 41

Not pure perl, it needs some other executable, namely cat, present and findable in the $PATH. But if it is present, it can be assumed as just a command available to perl, so why not. – Golar Ramblar – 2017-05-12T20:16:32.353

3

Node.js, 66 63 bytes

p=process;p.stdout.write(require('fs').readFileSync(p.argv[1]))

Doesn't use console.log, which appends a newline.

Félix Saparelli

Posted 2015-10-29T21:54:13.240

Reputation: 141

1You can save a few bytes by using the synchronous api: p=process;p.stdout.write(require('fs').readFileSync(p.argv[1])) – TehShrike – 2015-11-02T19:20:09.043

1Why not console.log(require('fs').readFileSync(process.argv[1]))\n for 57 bytes? – Conor O'Brien – 2016-09-30T00:14:02.300

This doesn't always work. Say the file is named test.js. It is valid to invoke it by running node test, which will cause this to throw an error. – Patrick Roberts – 2017-01-10T11:35:42.900

3

C, 31 bytes

main(){system("cat "__FILE__);}

The bash solution is so short, so why not base a C solution on it?

ugoren

Posted 2015-10-29T21:54:13.240

Reputation: 16 527

2

, 2 chars / 6 bytes (noncompeting)

ℹ⬮

Try it here (Firefox only).

The ℹ function both returns and pushes to the stack the source code. There is automatic outputting, so the contents of the stack will be outputted. Therefore, the source code will be outputted.

Mama Fun Roll

Posted 2015-10-29T21:54:13.240

Reputation: 7 234

Does this read the source file, or a copy of the source code? – lirtosiast – 2015-10-30T01:59:40.180

Here's the line in the interpreter source with the function. It's not really a file-based interpreter, but it reads the textarea value (aka the code). – Mama Fun Roll – 2015-10-30T02:31:04.680

You made this change an hour ago. Would your code have worked with the previous version?

– Dennis – 2015-10-30T02:47:44.297

@Dennis I actually made that change before seeing this challenge. It was because I didn't like the original output format. – Mama Fun Roll – 2015-10-30T02:53:02.633

3

@molarmanful Nevertheless, according to site policy, this is a noncompeting answer due to the fact that it uses a version of your language created after the challenge was posted.

– Doorknob – 2015-10-30T03:03:09.063

Alright, added disclaimer. – Mama Fun Roll – 2015-10-30T03:04:23.007

2

Java - 214 194

import java.io.*;class Q{Q(){try{System.out.print(new BufferedReader(new FileReader(getClass().getName()+".java")).readLine());}catch(Exception e){}}public static void main(String[]a){new Q();}}

Reduced a lot with using @VoteToClose method of finding the filename for java.

Readable version:

import java.io.*;

class Q {
        Q() {
                try {
                        System.out.print(new BufferedReader(new FileReader(getClass().getName()+".java")).readLine());
                } catch(Exception e) {}
        }
        public static void main(String[] a) {
                new Q();
        }
}

NOTE: The readable version doesn't actually work, it just reads the first line. Just to show what the code is doing

Cruncher

Posted 2015-10-29T21:54:13.240

Reputation: 2 135

I posted a Java answer as one of the first answers. :P But, just in case you want to narrow this down more, you can remove public from the class declaration. Also, I might steal your method of getting a class name for my answer. ;) – Addison Crump – 2015-10-30T17:19:36.603

2

C#, 153 bytes

class A{static void Main(){new A();}A([System.Runtime.CompilerServices.CallerFilePath]string s=""){System.Console.Write(System.IO.File.ReadAllText(s));}}

Readable version:

class A
{
    static void Main()
    {
        new A();
    }

    A([System.Runtime.CompilerServices.CallerFilePath] string s = "")
    {
        System.Console.Write(System.IO.File.ReadAllText(s));
    }
}

Thanks to @Johnbot for the idea to use CallerFilePathAttribute, which avoids any kind of name hardcoding!

Brian Reischl

Posted 2015-10-29T21:54:13.240

Reputation: 121

I do smell elements of my answer in this! Well done! +1 And welcome to the community! – Addison Crump – 2015-10-30T19:01:57.530

1

It's possible to get the source file name using the CallerFilePathAttribute.

– Johnbot – 2015-11-02T14:18:05.160

1You save 26 characters with string s instead of string sourceFilePath. – Comintern – 2015-11-02T23:49:13.010

I think you can save another 8 bytes if you add using System; at the top and omit System. in all namespace qualifiers (at least I think it worked that way, it's been some years since I've worked with C#) – hoffmale – 2015-11-03T08:58:55.350

@Comintern - good catch, thanks. That's what I get for doing it in a hurry. – Brian Reischl – 2015-11-03T14:35:26.187

2@hoffmale - that doesn't actually work. The using clause doesn't import sub-namespaces, just classes. So it would let me replace System.Console with just Console, but not System.IO with just IO. I could use an alias, using S = System; and shorten the uses of it, but that ends up being a wash. – Brian Reischl – 2015-11-03T14:43:26.797

ah, so that was only for classes... thanks for clarifying ^^ – hoffmale – 2015-11-03T15:39:04.203

2

Scala(2.10), 101 bytes

import scala.reflect.io.File;object A extends App{print(File(getClass.getName.head+".scala").slurp)}

Similar to the Java and C# answers. The only "interesting" parts here are the .head to drop the $ from the class name and the slurp method (which I'd never seen before) to read the file in as a String.

n0741337

Posted 2015-10-29T21:54:13.240

Reputation: 130

Cool, I didn't know that method existed in scala. Mine is slightly longer using groovy. – J Atkin – 2015-11-03T14:12:53.557

2

Java 8, 133 125 Bytes (or 150 142 slightly cleaner)

Based on @VoteToClose's answer but choosing Files.copy and thus avoiding the intermediate String creation needed to call System.out:

import java.nio.file.*;interface A{static void main(String[]a) throws Exception{Files.copy(Paths.get(A.class.getName()+".java"),System.out);}}

or hard-coding the class-name even more:

import java.nio.file.*;interface A{static void main(String[] a)throws Exception{Files.copy(Paths.get("A.java"),System.out);}}

Cleaned up:

import java.nio.file.*;

class A {
    public static void main(String[] a) throws Exception {
        Files.copy(Paths.get("A.java"), System.out);
    }
}

janschweizer

Posted 2015-10-29T21:54:13.240

Reputation: 151

Welcome to PPCG! (Programming Puzzles and Code Golf). Nice first answer! – J Atkin – 2015-11-03T14:17:46.310

This is almost invalid, as we were told to not hardcode a filename. – Addison Crump – 2015-12-05T00:28:58.547

2

JavaScript (node.js), 65

with(process)require('fs').createReadStream(argv[1]).pipe(stdout)

CR Drost

Posted 2015-10-29T21:54:13.240

Reputation: 949

2

Python 2, 27 bytes

print next(open(__file__))

Python 3, 28 bytes

print(next(open(__file__)))

Byte count includes new line.

Oddthinking

Posted 2015-10-29T21:54:13.240

Reputation: 121

My first contribution: harsh criticism welcomed. – Oddthinking – 2015-11-03T13:48:34.190

1

SmileBASIC, 69 68 bytes

LOAD"PRG1:"+PRGNAME$(0),FALSE
PRGEDIT 1
FOR I=0 TO 3?PRGGET$();
NEXT

Load the program into slot 0 (the default slot), and run!

Explanation

LOAD"PRG1:"+PRGNAME$(0),FALSE  load the source code into program slot 1
PRGEDIT 1                      open program slot 1 for editing
FOR I=0 TO 3                   loop 3 times { (no newline here)
?PRGGET$();                      print line, supressing extra newline
NEXT                           }

The ,FALSE on LOAD is required to supress a confirmation dialogue. I wasn't sure if this was required so I threw it in anyways (seems like it should be).

The extra setup of loading the source code into the neighbouring slot is required as SmileBASIC can't read or write from the currently loaded source code for some reason (it clearly reads it to load it into the other slot, but whatever).

As the output format isn't specified, you might be able to get away with just using the first line and claiming the output is found on slot one (which is one tap away) for 29 bytes.

redstarcoder

Posted 2015-10-29T21:54:13.240

Reputation: 1 771

1FALSE in SB just means 0, because SB doesn't have a boolean type. Conditionals (== != < > <= >= || &&) evaluate to 0 when false and 1 when true (with the exception of || and && which evaluate to 3 when the left term is a string; nobody knows why.) Any nonzero number is truthy, as well as all strings, even empty ones. NaN is always falsy and never equals itself. Arrays can't be compared though. Anyway, my point is, turn FALSE into 0 and save 4 characters. You could probably get away with allowing the loading screen but idk. – snail_ – 2017-01-09T14:06:03.450

Thanks @snail'! That's exactly the kind of information I needed to get assimilated in golfing with SmileBASIC! I'll update my answer soon. – redstarcoder – 2017-01-09T17:10:26.567

1

SmileBASIC, 26 bytes (newline at end)

Saw @redstarcoder 's answer and wanted to out-golf it. I'm not sorry.

?LOAD("TXT:"+PRGNAME$());

This exploits the fact that PRG is just a resource subtype of TXT (it's literally the same file format with a different icon) and loads the source file into a string. It's then simply printed.

I removed unneeded whitespace wherever the parser would let me, and put it all on one line for show. ? is just a shorthand for PRINT. The ; at the end ensures the PRINT doesn't add an extra newline. This one also doesn't disable the load dialog popup, but whatever.

If you remove the newline using a program that deletes the last character (since SB automatically adds a LF whenever you save through the editor) you can also remove the semicolon, bringing the answer down to 24 bytes. I didn't do this though, because I consider it kinda underhanded.

snail_

Posted 2015-10-29T21:54:13.240

Reputation: 1 982

Being "kinda underhanded" is probably ok in a challenge called "A 'cheating' quine" – 12Me21 – 2017-01-24T06:45:19.417

1

GW-BASIC / Applesoft BASIC / IBM BASIC / Commodore BASIC,  6 bytes

1 LIST

Pretty simple. No matter where you loaded the program from or how much is in it, it will always print everything in the program buffer, including itself.

MD XF

Posted 2015-10-29T21:54:13.240

Reputation: 11 605

1

Burlesque - 25 bytes

With-IO

,%____FILE?rfQ

Disclaimer: I've just added ____FILE because I/O support is still very rudimentary and there was no way of detecting the name of the file. Otherwise this would have been impossible. I/O built-ins aren't available in default builds but can be activated by using ghc ... -DHAVE_IO_UNSAFE ....

Without-IO:

,#Q2 SH ~- ",#Q" \/ .+ sh

Explanation: Burlesque is nasty.

Actual explanation: #Q looks at its own source code and pushes the code that is left in the "execution pipeline" onto the stack. In otherwords: #Q pushes all the code that is to the right to the stack. However, #Q does not look at ALL the source code just what is left in the "execution pipeline of the current execution context":

blsq ) 2ro{#Qj}m[
{1 {j} 2 {j}}

The #Q here is only able to see the j due to the execution context.

On a side-note: Burlesque has other modifiers that allow you to modify code such as for example #q which allows you to overwrite the remaining code in the execution pipeline of the current execution context:

blsq ) 3 4 {?*}#q?+
12

{?*}#q overwrites the ?+ with ?*. With #J we can inject/delay a piece of code by appending it to the execution pipeline:

blsq ) 3 4 {J?*}#J?+
49

The #J here appends J?* to the ?+.

mroman

Posted 2015-10-29T21:54:13.240

Reputation: 1 382

Hm, I'm not sure this satisfies "You must use file I/O to read the source code". – Ørjan Johansen – 2018-11-23T17:35:13.247

Oh, right. I should stop stopping prematurely while reading. – mroman – 2018-11-23T17:36:53.517

Meh. If it's allowed for APL to read code from "in-memory" then I can do that too ;) – mroman – 2018-11-23T18:04:19.260

1

VBScript, 67 bytes

CreateObject("WScript.Shell").Run "cmd /K type "&Wscript.ScriptName

Comintern

Posted 2015-10-29T21:54:13.240

Reputation: 3 632

1

Aubergine, 22 bytes, noncompeting

The tab character at the end signals end of file, and the interpreters all crash without it. It's cool that this challenge showed up on my radar this week since I just finished golfing this for the wiki.

-a1+a1=oA=Bi-BA:bB=ia   

I'll explain how it works later. It does not use file I/O but it very much does read its listing, and it is definitely cheating.

quintopia

Posted 2015-10-29T21:54:13.240

Reputation: 3 899

1

Groovy 92 bytes

Shorter than the other groovy answer, in addition to being filename agnostic.

print new Error().stackTrace*.fileName.collect{it?new File(it):null}.find{it?.exists()}.text

No newline at end of file.

Wesley Wolfe

Posted 2015-10-29T21:54:13.240

Reputation: 101

1

Vitsy, 4 bytes

This language feature is newer than this question, but not made for this question.

iG`Z

i     Grab input. Since there is no input, it pushes -1 to the stack.
 G    Get the class name of the referenced class. -1 refers to the current class.
  `   Read the file under the name of the stack's contents and push all of it to the stack.
   Z  Output everything in the stack.

As of November 24, class commands allow for referencing other programs accessible by disk, or 'classes'. Normally, it'd be used something like this:

00k

;u someothervitsyfile

Where I execute the 0th line (the first line) of the 0th index of the uses list ('someothervitsyfile'). I can get its name with G like so:

0GZ

;u someothervitsyfile

And, if I have the name, I can get its contents like so:

0G`Z

;u someothervitsyfile

But the special cases of this are -2 and -1, where -2 references the superclass (as defined by ;e) and -1 references the current class.

So, to get the name of the current class, I use -1, get its name, and, with its name being the only thing in the stack, I pull its contents with `.

Very fancy.

You cannot try this online, as it has been disabled to prevent reading server files.

Addison Crump

Posted 2015-10-29T21:54:13.240

Reputation: 10 763

1

Mouse-2002, 8 bytes

Expects to be put in a file called MOUSE.001. (Files with the names MOUSE.nnn are the only files Mouse knows how to perform I/O on. I didn't write the interpreter.)

If the EOF char at the end of the file, which is printed to the terminal, crashes your terminal, it's not my fault and I consider this a feature, not a bug.

(1 &F!')

Additionally, technically this is undefined behaviour (though most of Mouse is undefined except in practice) because it promises that the file's length is at least as long as the while(true). If this hangs your system because it's a loop, save your work, run git commit && git push, and don't say I didn't warn you.

cat

Posted 2015-10-29T21:54:13.240

Reputation: 4 989

1

Lua, 31 Bytes

print(io.open(arg[1]):read'*a')

The Arg table contains the following in lua.

{Filename, Command Line Argument1, Command Line Argument 2, ...}

ATaco

Posted 2015-10-29T21:54:13.240

Reputation: 7 898

That seems to be more like {[-1]="Interpreter", [0]="Filename", [1]="Command Line Argument1, [2]="Command Line Argument 2"}. So you should read arg[0] instead. – manatwork – 2018-09-24T20:18:34.073

0

Perl, 9 bytes

#!/bin/dd

Perl allows you to change the parser while the file's being read. One thing you can do is to change the program that parses the file entirely via the use of #! on the first line; this feature was intended to allow the use of Perl to fix a system on which shebangs didn't work correctly. dd with no parameters copies standard input to standard output (followed by some statistics on standard error which shouldn't matter), thus is a suitable program to use for a cheating-quine (because Perl reloads the file from disk to give to dd.)

user62131

Posted 2015-10-29T21:54:13.240

Reputation:

1That is not perl. The kernel reads the first two bytes and interprets them, finds #!' and thus continues to read the line, finds/bin/ddand thus launches/bin/dd, given the file as argument todd`. NO PERL INVOLVED AT ALL. – Golar Ramblar – 2017-05-12T20:23:10.133

1@GolarRamblar: It is Perl. You can run perl followed by the filename, and perl itself will do the #! translation. It uses slightly different rules from the kernel for interpreting #! lines, in fact. (Perl originally added this feature so that if you were using an operating system, like Windows or DOS, that does not support #! lines, you could nonetheless use #! scripts by setting Perl as the interpreter for their file type.) – None – 2017-05-12T20:31:20.603

0

stacked, 11 bytes

program put

Try it here!

Outputs the program stored in the program variable. Simple!

Conor O'Brien

Posted 2015-10-29T21:54:13.240

Reputation: 36 228

0

Node.js, 63 bytes

Uses the __filename global to obtain its file path as opposed to process.argv[1], which can be flawed:

require('fs').createReadStream(__filename).pipe(process.stdout)

Patrick Roberts

Posted 2015-10-29T21:54:13.240

Reputation: 2 475

0

HTML and Javascript, 88 Bytes

<head></head><body><svg onload="alert(document.documentElement.innerHTML)"></svg></body>

Had to add <head></head><body></svg></body> because that's what the browser outputs regardless of the original file.

user64039

Posted 2015-10-29T21:54:13.240

Reputation:

#HTML and Javascript, 109 Bytes# <html><head></head><body onload="alert('<html>'+document.documentElement.innerHTML+'</html>')"></body></html> @Masterzagh, Actually browsers add html tag too. Sorry, Couldn't add a comment as I don't have enough reputation. – prathapa reddy – 2017-01-10T12:32:28.000

I tested it on firefox and chrome and neither added the html (at least on the alert which is what we're interested in). @prathapareddy – None – 2017-01-10T16:45:43.653

0

Lua, 32 29 bytes

3 bytes saved thanks to Jonathan Frech

print(io.open(arg[0]):read())

Try it online!

How?

Lua uses the arg table to store it's arguments, the script name is always stored at index 0 of this table despite the fact there are no further arguments. After using this table to get the name of the file, printing it was as easy as opening the file and reading its content.

Marcio Medeiros

Posted 2015-10-29T21:54:13.240

Reputation: 51

I think you can toss your variable and save three bytes. – Jonathan Frech – 2018-09-24T20:40:34.070

It is interesting, how your script's file name is stored at 'index' zero, even though LUA is 1-indexed ... And it goes on: arg[-1] contains the language name ... – Jonathan Frech – 2018-09-24T21:49:40.427

0

Perl 6 / POSIX shell, 16 bytes

run 'cat',$?FILE

Try it online!

nwellnhof

Posted 2015-10-29T21:54:13.240

Reputation: 10 037

0

R, 44 bytes

cat(scan(sub(".*=","",commandArgs()[4]),""))

Prints to stderr as well. If that's not allowed this works for 46 bytes:

cat(readLines(sub(".*=","",commandArgs()[4])))

Run these from the command line using Rscript.

ngm

Posted 2015-10-29T21:54:13.240

Reputation: 3 974

0

CopyPasta Language, 32 bytes

But I think this is interesting enough to compete here.

CopyFile
TheFuckingCode
Pasta!

Copy the source code, display the clipboard, and stop the program.

user85052

Posted 2015-10-29T21:54:13.240

Reputation:

1

Worthy of note: This language did not have an interpreter when you posted this, so it would have been invalid. As of rn, I have implemented an interpreter for the language, since the linked interpreter on the esolang is a dead link

– Conor O'Brien – 2019-10-03T03:06:08.080

0

Tcl, 37 bytes

chan copy [open [info script]] stdout

The older, more self explanatory version (43 bytes):

puts -nonewline [read [open [info script]]]

slebetman

Posted 2015-10-29T21:54:13.240

Reputation: 629

0

Lua, 59 characters

print(io.open(debug.getinfo(1,'S').source:sub(2)):read'*a')

Sample run:

bash-4.3$ lua quine.lua 
print(io.open(debug.getinfo(1,'S').source:sub(2)):read'*a')

manatwork

Posted 2015-10-29T21:54:13.240

Reputation: 17 865

0

C++, 93 bytes

#include <iostream>
#include <fstream>
main(){std::fstream f(__FILE__);std::cout<<f.rdbuf();}

I wanted to do a “pure” C++ version…and I have to say that it doesn't do too badly: it's down to 54 bytes if I can do without including the headers.

arjanen

Posted 2015-10-29T21:54:13.240

Reputation: 151

0

A Groovy 103 100 bytes!

Yes I know I'm evil

I stay in line with the other JVM answers (Java, Scala) to make this answer.

class X{static def main(String[]a){new X()}
def X(){print new File(getClass().name+'.groovy').text}}

J Atkin

Posted 2015-10-29T21:54:13.240

Reputation: 4 846

0

C (Win32), 36 bytes

main(){CopyFileA(__FILE__,"CON",0);}

CopyFile makes the challenge easier in Win32 than in POSIX or ISO C, that's for sure. You however need to call the compiler with stdcall as its default calling convention.

arjanen

Posted 2015-10-29T21:54:13.240

Reputation: 151

0

Emacs Lisp (93 Bytes)

:; emacs -Q -script $0; exit
(find-file (nth 2 command-line-args))
(message (buffer-string))

The first line calls the program in your normal shell and exits (to prevent the rest also being evaluated). command-line-args will be a list of three strings, "emacs", "-scriptload" and the name of your file. find-file will open that file and make it the current buffer, so that (message (buffer-string)) will write it to stdout as -script redirects messages there.

It should be noted, that -Q may not be necessary if your Emacs doesn't print other messages during startup, so that the first line could be shortened to #!emacs -script, shortening this to 81 bytes, but as it is highly unlikely that init and site-lisp files produce 0 messages at all, this cannot be assumed.

Lord Yuuma

Posted 2015-10-29T21:54:13.240

Reputation: 587

0

APL, 8 bytes (non-competing)

APL does not use source files for single functions, rather a whole workspace (a machine-readable collection of token-representations) is saved and loaded, so I guess this is not allowed:

f     
⎕CR'f'

(⎕CR is Character Representation) as the program reads its current definition in memory (the loaded workspace), which may have been modified from the source in the file.

Adám

Posted 2015-10-29T21:54:13.240

Reputation: 37 779

0

Matlab, 32 bytes

disp(fileread([mfilename,'.m']))

flawr

Posted 2015-10-29T21:54:13.240

Reputation: 40 560