# 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? Oct 29, 2015 at 22:04
• @isaacg IMHO That's not a quine, since it is not the source code.
– user42643
Oct 29, 2015 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. Oct 29, 2015 at 22:26
• I agree with @feersum though, that requiring a specific file name makes this challenge way to trivial.
– user42643
Oct 29, 2015 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). Nov 1, 2015 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, 2015 at 10:51

# Bash, 6 bytes

cat $0  Basically. • It does not print a newline. Oct 29, 2015 at 22:06 • cat does not append a newline (at least on my system). Oct 29, 2015 at 22:06 • @isaacg cat prints the content of the supplied file byte per byte. Oct 29, 2015 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 Oct 29, 2015 at 23:07 • Will this work if the file is named -e ? Oct 30, 2015 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. Oct 29, 2015 at 23:39 • Perhaps cheating a bit, but couldn't you rename your bin folder and the cat program to shorten the path? Oct 30, 2015 at 9:54 • I'm not suggesting you do btw. I'm suggesting you could Oct 30, 2015 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, 2015 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… Oct 30, 2015 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. Oct 29, 2015 at 22:51 • @DigitalTrauma It's because of your avatar, of course Oct 30, 2015 at 6:27 • Actually, puts can be used, you just need to read fewer characters. Oct 31, 2015 at 1:41 • @kasperd Yes, guaranteed by C89 Nov 1, 2015 at 0:06 • 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. May 24, 2017 at 3:04 # 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! Jul 8, 2021 at 11:55 # 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! Nov 3, 2015 at 9:19 • readfile is also 21: <?readfile(__FILE__);. Nov 3, 2015 at 15:42 • Right, it doesn't need <?= Nov 3, 2015 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? Nov 1, 2015 at 2:03
• @Eevee nope, it gets angry Nov 1, 2015 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> Nov 2, 2015 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? Nov 2, 2015 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";" Nov 2, 2015 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 Oct 29, 2015 at 23:03
• Working on getting it to work. Oct 29, 2015 at 23:07
• read path to me seems to work for me. El Cap. Oct 29, 2015 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. Oct 30, 2015 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. Nov 2, 2015 at 21:24
• @Skyler You're absolutely correct. Nov 2, 2015 at 21:34
• How does this work in Python 3, which needs parens for print? Nov 2, 2015 at 21:36
• Python 3 should be print(open(__file__).readline()) followed by a newline. Nov 2, 2015 at 21:37
• Your Python 3 example says Python 2 rather than Python 3 May 25, 2016 at 22:39

# 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, 2015 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, 2015 at 0:25
• That's not what the comma does. It appends a space instead of a newline.
– xsot
Oct 30, 2015 at 1:00
• could use ␤ to indicate a semantically-important newline Nov 1, 2015 at 2:02

# Batch, 9 8 Bytes

@type %0


Saved a byte thanks to @Joshua

• You can save a byte by eliminating the trailing %. Oct 30, 2015 at 4:02

# AutoIt, 34 bytes

Outputs itself to the clipboard:

ClipPut(FileRead(@ScriptFullPath))


# Ruby, 14

$>.<<IO.read$0

• Nice use of . to avoid parentheses Jul 3, 2017 at 6:21

# 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. Oct 30, 2015 at 4:03
• Well, this is code golf. My code produces the desired output so it's a valid submission.
– xsot
Oct 30, 2015 at 4:16
• @xsot In that case, you should probably list the compiler version + options; otherwise this might not be verifiable. Oct 30, 2015 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, 2015 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, 2017 at 19:43

# 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? Oct 30, 2015 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 ;-) Oct 30, 2015 at 12:36
• The method is actually a bit different, good one! Oct 30, 2015 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. Oct 30, 2015 at 0:44 • its not guaranteed to especially if the script is running silently Oct 30, 2015 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. Oct 30, 2015 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... Oct 30, 2015 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. Oct 30, 2015 at 13:03 ## C, 31 bytes main(){system("cat "__FILE__);}  The bash solution is so short, so why not base a C solution on it? # Ruby, 15 bytes $><<IO.read($0)  • I've converted this to a community wiki because it isn't your own work. Oct 29, 2015 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__$? Oct 29, 2015 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. Oct 29, 2015 at 23:41

# 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. Nov 13, 2015 at 18:04 # Haskell, 63 bytes For science! import System.Environment main=getProgName>>=readFile>>=putStr  • Only works with the runhaskell command. Very cool though Nov 2, 2015 at 22:44 # 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. # 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". Oct 30, 2015 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])) Nov 2, 2015 at 19:20 • Why not console.log(require('fs').readFileSync(process.argv[1]))\n for 57 bytes? Sep 30, 2016 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. Jan 10, 2017 at 11:35 # 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)  • Remove ";" at the end, save 1 byte :) Jul 3, 2017 at 7:44 • @ЕвгенийНовиков You're right, not sure why I left that in back then. It seems like I didn't count it though. Jul 4, 2017 at 11:07 • You don't need the <title>x</title> Jul 8, 2021 at 21:21 • @VFDan A well-formed standalone HTML document needs a title of at least one character, even if browsers will make do without it. I thought it was a nice bit of trivia to display in this silly answer. Jul 9, 2021 at 6:39 # Rust, 45 bytes fn main(){print!("{}",include_str!(file!()))}  Try it online! The file macro expands to the file it's invoked in's file path, the include_str macro expands to a string literal containing the contents of the file at the specified path, and the print macro prints. # 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. May 12, 2017 at 20:16