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

cat $0  Basically. • It does not print a newline. – Addison Crump Oct 29 '15 at 22:06 • cat does not append a newline (at least on my system). – a spaghetto Oct 29 '15 at 22:06 • @isaacg cat prints the content of the supplied file byte per byte. – Dennis Oct 29 '15 at 22:17 • @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 Oct 29 '15 at 23:07 • Will this work if the file is named -e ? – Mark Plotnick Oct 30 '15 at 6:05 # 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  • I like this. Not sure if it qualifies as a "language," though. – Kevin Oct 29 '15 at 23:39 • Perhaps cheating a bit, but couldn't you rename your bin folder and the cat program to shorten the path? – James Webster Oct 30 '15 at 9:54 • I'm not suggesting you do btw. I'm suggesting you could – James Webster Oct 30 '15 at 9:54 • @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 Oct 30 '15 at 10:38 • @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 Oct 30 '15 at 23:08 # 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. • You could use printf instead of puts to avoid a trailing newline. – feersum Oct 29 '15 at 22:51 • @feersum yes, good catch – Digital Trauma Oct 29 '15 at 22:52 • @DigitalTrauma It's because of your avatar, of course – Peter Olson Oct 30 '15 at 6:27 • Actually, puts can be used, you just need to read fewer characters. – user4098326 Oct 31 '15 at 1:41 • @kasperd Yes, guaranteed by C89 – Digital Trauma Nov 1 '15 at 0:06 # 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__). • 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 Nov 3 '15 at 9:19 • readfile is also 21: <?readfile(__FILE__);. – primo Nov 3 '15 at 15:42 • Right, it doesn't need <?= – Fabian Schmengler Nov 3 '15 at 15:55 # 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

## Perl, 15 bytes

open 0;print<0>


Saved 3 bytes thanks to @ThisSuitIsBlackNot!

• You can save 3 bytes with open 0;print<0> – ThisSuitIsBlackNot Nov 2 '15 at 3:45
• @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 Nov 2 '15 at 5:44 • 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

# 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

# Vyxal 2.4.0, 50 bytes

\");VY_print(chr(96)+code.split('\n')[3][15:-4])#


Vyxal doesn't have a way to read files, but in v2.4.0 and prior, there was an ACE exploit that allowed for arbitrary python to be executed.

### The ACE:

Vyxal is a transpiled language, meaning that every command in a program is converted to some python code, and then all of the python code is combined together and executed.

When pushing a string, all that was done to the string in transpilation was changing " to \\\", then appending it to the stack. This meant that a string \"); # would become \\");#. On its own, this means nothing, but when considered in the transpiled code, it is much more useful.

When viewing the transpiled code (which you can do for any Vyxal program using the c flag), you can see that the snippet \\"); # is transpiled to the following python code:

stack.append("\\"); #\n")


Instead of pushing the string that we told it to, it simply pushed \, followed by a comment. In theory, we could put any python code between the ; and the #, which is what we do in this program.

### The program:

In this program, the payload (the python code that we actually care about) is the following:

VY_print(chr(96)+code.split('\n')[3][15:-4])


This has several parts to it, so lets pick it apart bit by bit.

VY_print is the printing function that is defined internally in Vyxal. I used this function instead of print because it disables the implicit output that Vyxal normally has. This prints the final string, which will hopefully be the same as the program.

When the program is transpiled, the transpiled code is saved in the code variable. This variable is used in the program to read the source code, which makes this a cheating quine.

However, the code variable also contains a header that initializes a few variables, such as the stack. To combat this, we split the code on newlines and get only the fourth line, which is where our code is.

Unfortunately, this line also has the stack.append..., and the comment at the end, neither of which are part of our quine. Because of this, we need to take only the 16th through 5th-to-last characters in the string, which we do with [15:-4].

Finally, our code has a backtick at the beginning to start the string, so we add one to the beginning of the output with chr(96), since the ASCII value of  is 96.

• Wooooo crappy programming ftw! – lyxal Jul 8 at 11:55

# 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

# 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()? – fabiofili2pi Oct 30 '15 at 8:18
• It's CodeGolf not CodeReview! ;) – fabiofili2pi 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

# 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

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

• Can't you just do h'$__file__$? – kirbyfan64sos Oct 29 '15 at 23:34
• @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 Oct 29 '15 at 23:41

# 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 # Haskell, 63 bytes For science! import System.Environment main=getProgName>>=readFile>>=putStr  • Only works with the runhaskell command. Very cool though – HEGX64 Nov 2 '15 at 22:44 ## C, 31 bytes main(){system("cat "__FILE__);}  The bash solution is so short, so why not base a C solution on it? # 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))}  • This 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 Oct 30 '15 at 12:27 ## ><>, 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. # 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 # 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. # 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 # 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.

• Cool, I didn't know that method existed in scala. Mine is slightly longer using groovy. – J Atkin Nov 3 '15 at 14:12
• You are not allowed to assume the file extension is .scala`. – Makonede Jul 9 at 20:42