C/POSIX
This program uses the number of hard links to its own executable as counter of how often it was called. It creates the new hard links in the directory it was started from (because that way it's guaranteed to be on the same file system), which therefore needs write permission. I've omitted error handling.
You better make sure that you have no important file with the same name as one of the created hard links on that directory, or it will be overwritten. If e.g. the executable is named counter, the hard links will be named counter_1, counter_2 etc.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
/* get persistent counter */
struct stat selfstat;
stat(argv[0], &selfstat);
int counter = selfstat.st_nlink;
/* determine digits of counter */
int countercopy = counter;
int digits = 1;
while (countercopy /= 10)
++digits;
/* increment persistent counter */
char* newname = malloc(strlen(argv[0]) + digits + 2);
sprintf(newname, "%s_%d", argv[0], counter);
link(argv[0], newname);
/* output the counter */
if (counter & (counter-1)) // this is zero iff counter is a power of two
printf("%d\n", counter);
else
{
/* determine which power of 2 it is */
int power = 0;
while (counter/=2)
++power;
printf("2^%d\n", power);
}
return 0;
}
Example run (the first line resets the counter, in case the executable has already been run):
$ rm counter_*
$ ./counter
2^0
$ ./counter
2^1
$ ./counter
3
$ ./counter
2^2
$ ./counter
5
$ ./counter
6
$ ./counter
7
$ ./counter
2^3
$ ./counter
9
$ ls counter*
counter counter_2 counter_4 counter_6 counter_8 counter.c
counter_1 counter_3 counter_5 counter_7 counter_9 counter.c~
3why does it output
0in the first run? – mniip – 2014-03-04T05:19:11.123did you mean "where
n = 2^x? Otherwise the second time the output would be2^4, the fourth time2^16and so on. – John Dvorak – 2014-03-04T05:23:58.707@mniip both typos. I probably should've read that more carefully... :P – Jwosty – 2014-03-04T05:27:08.040
4Umm...
1is a power of two.2^0=1– John Dvorak – 2014-03-04T05:32:09.973@JanDvorak Uggh, you're right. – Jwosty – 2014-03-04T05:32:38.450
1You still say
x = 2^xrather thann = 2^x– John Dvorak – 2014-03-04T05:36:22.353Is there any rule about how we count the number of times we've been run? I've just posted an answer that uses an external data file, but as I was finishing it it occurred to me that you might have wanted us to be modifying our own source code instead (which would only be a little bit harder). – Blckknght – 2014-03-04T06:13:31.033
@Blckknght I thought about doing that, but people will up vote the more creative one more. – Jwosty – 2014-03-04T14:09:50.883