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~
0
in the first run? \$\endgroup\$n = 2^x
? Otherwise the second time the output would be2^4
, the fourth time2^16
and so on. \$\endgroup\$1
is a power of two.2^0=1
\$\endgroup\$x = 2^x
rather thann = 2^x
\$\endgroup\$