# Count how many characters are in the program's source

Write a program that counts and prints the number of characters in it's own source code to standard output.

The number must be generated from counting the characters.

This Ruby solution would not be allowed:

puts 6


because it is not calculated. Spaces, tabs, new lines, etc should be counted.

The program must be smallest possible in any programming language.

• If you post another challenge, I strongly suggest using this template. May 15 '14 at 13:27
• My guess, make a program that will count how many characters are used in the programs code, so basicly count the characters in your source and make it as short as possible. Is this really being downvoted for poor english? May 15 '14 at 13:27
• I made a winner! PHP, 1 character: 1 May 15 '14 at 13:28
• Something like echo 'wc -c $0' > x ; sh x... I think this is a nice question, maybe the rules should be a little more precise... – user19214 May 15 '14 at 13:33 • Whatever tags it should have, it's a rubbish question. It's like making a cheating "quine" without even having the interest of being a quine. May 16 '14 at 20:11 ## 29 Answers # Bash, 10 Pretty boring, but: • Prints the code size in bytes, and nothing else. • Filename may contain spaces. Make sure that the file doesn't have a new line at the end! If it does, it will output 11. wc -c<"$0"


If the file doesn't have spaces in its name, you can get 8 characters:

# perl, 9 bytes

No trailing newline.

print-s$0  Running it looks like this: $ echo -n 'print-s$0' >/tmp/foo.pl$ perl /tmp/foo.pl ; echo
9

• -M5.01 is free, so you can reduce this by two bytes by using say instead of print. (Tested on Strawberry 5.20.2.) May 16 '16 at 17:41

# BASH (builtins only) - 18

$cat bash ; echo # no final newline in file a=<$0
echo ${#a}$ ls -l bash
-rwxr-xr-x 1 yeti yeti 18 18. Mai 07:11 bash
$./bash 18  ## Fortran 78 character*78::a;open(unit=9,file='c.f90');read(9,'(a78)')a;print*,len(a);end  File IO isn't the best in Fortran, so we have to waste space opening the file & then reading from it. Had I not specified the a78 (78 characters), then it would stop at the comma next to file (silly list-directed IO). # HTML + Javascript (jQuery): 48 Save this script as script.html and open it with a browser. <script>alert($('body').html().length)</script>

• You also need to include any library with a $ function. Otherwise this won't work. May 20 '14 at 13:57 # Python 31 Save the file as 'l' print len(file.read(file('l')))  Outputs 34 • Might as well name it l... Saves 3 chars May 18 '14 at 19:28 # Rebol, 40 print length? read system/options/script  # VIM - 43 Add this in your .vimrc file : :echo strlen(join(readfile(".vimrc")),"\n")  But it will only work if you are in your home when executing vim. More generic solution vim ~/.vimrc (46 chars) : :echo strlen(join(readfile(bufname("%")),"\n"))  • Your first solution seems to have one too many rightparens. Aug 12 '14 at 18:31 • @Aurel300 yup thx. fixed Aug 12 '14 at 21:08 # PHP - 22 <?=filesize(__FILE__);  # Python 3, 28 27 bytes I got 2̶8̶ 27 characters, plus file name and extension (4 in this case for 'f.py') The minimum value for this is 3̶2̶ 31, if there was a 1 letter file name and the .py exension: print(len(open("f.py").read()))  EDIT: The bite count is actually 27 rather than 28, thanks @mbomb007 for pointing that out • The byte count is wrong. Apr 27 '16 at 21:03 • Why not just f? Aug 11 '16 at 3:25 • @NoOneIsHere The program I use to execute the program doesn't run unless the file is a .py file, so it was out of habit that I put that. But, as you say, using f instead of f.py would lower the byte count from 31 to 28 (including the filename) Aug 11 '16 at 3:38 ## JavaScript 78 <script id="s"> function f(){document.write(document.getElementById("s").innerHTML.length);} </script>  • You may save 2 chars removing quotes from id="s" May 19 '14 at 11:46 • also, the stdout of javascript is alert so you may save lot of chars replacing the document.write May 19 '14 at 11:49 • This isn't pure javascript. Apr 27 '16 at 20:52 # J - 16 char J can read($0) itself too, you know! Not all that well, but...

echo#1!:1]1{ARGV


A more natural solution in the interpreter REPL, in which we do the normal quine thing and then take the length, costs 24 chars:

#(,2#{:),~'#(,2#{:),~'''


,~ appends the string to itself, (,2#{:) appends two copies of the trailing single quote, and # takes the length.

# Extended BrainFuck: 12

,(>+<,)>55+.


Usage:

beef ebf.bf < cnt.ebf > cnt.bf
beef cnt.bf < ent.ebf


Output:

C


Which is 12 in hex. If you add a linefeed in the file it will output a D for 13 so it's definitely counting the characters in the source.

• I wonder how fun it would be to program in something that adds GolfScript functionality to Extended BF...Makes me tempted to spec out a more fully featured BF derivative that combines a lot of things invented by other BF derivatives (limited networking support, early termination, timing from NetFuck, significant comment syntax and function/macro support from cbrain, multithreading support from Brainfork, etc.) with some things from GolfScript (like variables) and a few additions of mine for utility reasons (modules, anyone?). Aug 12 '14 at 6:16
• @impinball EBF has variables and macros and it would have been difficult to make LISP in it without it. A major design goal of EBF was that it should produce pure BF object code that runs under any BF implementation. Making just an interpeter/compiler that has added primitives like pbrain is IMO cheating. A cleaner approach to get feature like file I/O would be to implement message passing through stdin/stdout so that you could make a program X that implements the protocol that run standard brainfuck interpreter/compiler Y and intercept the I/O. Aug 12 '14 at 14:40
• Just leisurely wondering. I wouldn't add half a million primitives. I was pondering the idea of modular BF that includes some useful other stuff like what EBF and NetFuck has. Make a more useful(ish) BF. I wouldn't use pbrain's comment syntax, because it would be easier to use the more common empty register comment. I still would want to include native file I/O, but not by flooding with primitives. Aug 12 '14 at 14:45
• @impinball EBF is a more useful BF since it provides more primitives front end without demanding it from it's back end. BTW: I have made a joke compiler called BrainBack that is a Forth type language like GolfScript. I wrote the compiler in EBF and it compiles to EBF :) Aug 12 '14 at 14:48
• Ok... Could you reread my comment... I sent it earlier than I intended. Aug 12 '14 at 14:49

Hy (38 characters):

(defmain [n] (print (.read (open n))))


# dc - 8

Not sure if this is allowed, but calculates the length of the macro(the part in the square brackets and adds 4(which is the length of the part outside the macro)).

[Z4+p]dx


## Lua: 42

print(string.len(io.open('l',"r"):read()))


Pretty straight-forward, you must save the file as l and call it as lua l.

• In lua read only is the default, so you can remove the "r". You can use # instead of string.len to make it even shorter. Aug 12 '14 at 17:02

# K,13

1@$#,/0:.z.f;  / $ q a.k -q
13


# Python 3: 33 or 37

print(len(open(__file__).read()))


First if you only count the characters, second if you want to count the number of bytes.

## JavaScript (Node.js) - 60

console.log(require('fs').readFileSync(__filename).length);


# Java, 157 characters

Since nobody has done Java yet...

public class A{public static void main(String[]a) throws Exception{System.out.print(new java.util.Scanner(new java.io.File("A.java")).nextLine().length());}}

• Welcome to Programming Puzzles & Code Golf! Answers to code golf challenges here are typically prefixed with a header mentioning the language the code is written in and its amount of characters. I've edited it in for you this time, but it would be great if you could include one in your future code golf solutions. Thanks!
– Doorknob
Aug 12 '14 at 15:24
• Cause ya know, java. Apr 27 '16 at 20:54

## PHP - 44

Save this as c

<?$f=fopen("c","r");echo strlen(fgets($f));

• Why do you store $f? echo strlen(fgets(fopen("c","r"))); Apr 27 '16 at 21:00 • <?=strlen(fgets(fopen(c,r)));, 29 bytes: Neither c nor r need quotes; and echo-tag is shorter than echo. Dec 21 '16 at 19:38 ## JavaScript 42 - ES5 (function a(){alert((a+"()()").length)})()  37 - ES6 (a=x=>{alert((a+"(a=)()").length)})()  • And also, a self invoking function is longer, than actually calling it Apr 27 '16 at 21:07 # Javascript (pure - no HTML nor JQuery) 41 bytes function f() {alert((f+"f()").length)}f()  ## awk, 13 bytes $0=length($0)  Write it to a program file program.awk and $ awk -f program.awk program.awk
13


# RProgN, 3 bytes.

Q L


Simply, Q is the function that pushes the source code to the stack, and L is the function that gets the length of the string on top of the stack. The stack is then implicitly printed.

Try it online!

# Dyalog APL, 8 bytes

The niladic function f:

≢∊⎕NR'f'


Notice that this prints 10 because APL counts (and stores) the function header (name + newline). However, PPCG practice is not to count this header. The entire program can be displayed with

      ↑⎕NR'f'


Giving:

f
≢∊⎕NR'f'


⎕NR'f' the Nested (i.e. a list of character lists) Representation of f

∊ϵnlist (flatten)

≢ tally