# A “cheating” quine

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!

• Is a trailing newlines not present in the original file allowed? – isaacg Oct 29 '15 at 22:04
• @isaacg IMHO That's not a quine, since it is not the source code. – mınxomaτ Oct 29 '15 at 22:05
• You should state a requirement that it determine the actual filename instead of assuming a hard-coded string for the source location. – feersum Oct 29 '15 at 22:26
• I agree with @feersum though, that requiring a specific file name makes this challenge way to trivial. – mınxomaτ Oct 29 '15 at 22:33
• Can 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 Nov 1 '15 at 9:15

# 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

• feline functionalities :) – theB Oct 31 '15 at 10:51

• Yep. 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 Nov 2 '15 at 6:41 # 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.

• can you remove the second space? – Eevee Nov 1 '15 at 2:03
• @Eevee nope, it gets angry – Hotkeys Nov 1 '15 at 9:25

# osascript (AppleScript from the command line), 4033 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.

• See my edit to the OP – TheInitializer Oct 29 '15 at 23:03
• Working on getting it to work. – Addison Crump Oct 29 '15 at 23:07
• read path to me seems to work for me. El Cap. – Digital Trauma Oct 29 '15 at 23:15
• 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 Oct 30 '15 at 7:30

# 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

• This would also save 2 bytes in python3 because you could discard the end parameter. – Skyler Nov 2 '15 at 21:24
• @Skyler You're absolutely correct. – Celeo Nov 2 '15 at 21:34
• How does this work in Python 3, which needs parens for print? – Doorknob Nov 2 '15 at 21:36
• Python 3 should be print(open(__file__).readline()) followed by a newline. – Skyler Nov 2 '15 at 21:37
• Your Python 3 example says Python 2 rather than Python 3 – TheInitializer May 25 '16 at 22:39

# Batch, 9 8 Bytes

@type %0


Saved a byte thanks to @Joshua

• You can save a byte by eliminating the trailing %. – Joshua Oct 30 '15 at 4:02

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

• Does this run into the same problem with the trailing newline that the other submission did? – cole Oct 30 '15 at 0:21
• 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 Oct 30 '15 at 0:25
• That's not what the comma does. It appends a space instead of a newline. – xsot Oct 30 '15 at 1:00
• could use ␤ to indicate a semantically-important newline – Eevee Nov 1 '15 at 2:02

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

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(
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(
Paths.get(
A.class.getName()+".java"))));
}
}


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

• Why just not use A.class.getName()? – Fabio F. Oct 30 '15 at 8:18
• It's CodeGolf not CodeReview! ;) – Fabio F. Oct 30 '15 at 8:26
• @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 Oct 30 '15 at 17:39
• Can't you call the print statement inside the constructor and save yourself from setting a static variable? – Cruncher Oct 30 '15 at 17:45
• @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 Oct 30 '15 at 18:14

# AutoIt, 34 bytes

Outputs itself to the clipboard:

ClipPut(FileRead(@ScriptFullPath))


# Ruby, 14

$>.<<IO.read$0

• Nice use of . to avoid parentheses – Cyoce Jul 3 '17 at 6:21

# PowerShell, 393631 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.

• gc $MyInvocation.MyCommand.Path is enough. It will automatically print it out. – Andrew Oct 30 '15 at 0:44 • its not guaranteed to especially if the script is running silently – Chad Baxter Oct 30 '15 at 0:49 • 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 Oct 30 '15 at 0:51 • 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 Oct 30 '15 at 0:57 • 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 Oct 30 '15 at 13:03 # 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. • There is already an answer in Go - does this use the same method? – Addison Crump Oct 30 '15 at 12:20 • @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 Oct 30 '15 at 12:36 • The method is actually a bit different, good one! – Fabian Schmengler Oct 30 '15 at 13:27 # Ruby, 15 bytes $><<IO.read($0)  • I've converted this to a community wiki because it isn't your own work. – Alex A. Oct 29 '15 at 23:58 # 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. • This code invokes undefined behavior twice. – Joshua Oct 30 '15 at 4:03 • Well, this is code golf. My code produces the desired output so it's a valid submission. – xsot Oct 30 '15 at 4:16 • @xsot In that case, you should probably list the compiler version + options; otherwise this might not be verifiable. – Justin Oct 30 '15 at 7:16 • If 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 Nov 3 '15 at 0:44 • @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 May 31 '17 at 19:43 # Mathematica, 16 bytes FilePrint@$Input


Run it in script mode.

• I've been using Mathematica for many years and had never even heard of script mode. – Michael Stern Nov 13 '15 at 18:04

For science!

import System.Environment

• Only works with the runhaskell command. Very cool though – HEGX64 Nov 2 '15 at 22:44

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). • 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 Nov 3 '15 at 11:47 • @Sp3000 woops indeed, looks like I didn't read the challenge well enough. I'll add a disclaimer – Aaron Nov 3 '15 at 12:00 # F#, 54 Bytes printf"%s"(System.IO.File.ReadAllText __SOURCE_FILE__)  Usage: fsi --exec a.fsx  # Perl 5, 15 13 bytes Credit to the Bash solution for inspiring this: printcat$0


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

• 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 May 12 '17 at 20:16

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

• You can save a few bytes by using the synchronous api: p=process;p.stdout.write(require('fs').readFileSync(p.argv[1])) – TehShrike Nov 2 '15 at 19:20
• Why not console.log(require('fs').readFileSync(process.argv[1]))\n for 57 bytes? – Conor O'Brien Sep 30 '16 at 0:14
• 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 Jan 10 '17 at 11:35

## C, 31 bytes

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


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

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

• Welcome to PPCG! (Programming Puzzles and Code Golf). Nice first answer! – J Atkin Nov 3 '15 at 14:17
• This is almost invalid, as we were told to not hardcode a filename. – Addison Crump Dec 5 '15 at 0:28

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