2
\$\begingroup\$

Write a program that after running will show how many times it was ran before. You are only allowed to modify the executable itself (the code itself, or compiled version of your code), you cannot modify anything else or create new files.

Example:

$ ./yourprogram
0
$ ./yourprogram
1
$ ./yourprogram
2
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Somewhat less trivial example than y'old bash, in C:

#include <stdio.h>

int main(int argc,char **argv){
    const char *data="Da best marker in da world 0\0\0\0\0\0\0";
    FILE *f;
    int i;
    char c;
    long int pos;
    printf("%s\n",data+27);
    f=fopen(argv[0],"r+b");
    i=0;
    c=fgetc(f);
    while(!feof(f)){
        if(data[i]==c){
            i++;
            if(i==27)break;
        } else i=0;
        c=fgetc(f);
    }
    if(i!=27)return 1;
    i=0;
    pos=ftell(f);
    c=fgetc(f);
    while(c!='\0'){
        i=10*i+c-'0';
        c=fgetc(f);
    }
    i++; //The increment!
    fseek(f,pos,SEEK_SET);
    fprintf(f,"%d",i);
    fflush(f);
    fclose(f);
    return 0;
}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ How were you able to post an answer? \$\endgroup\$
    – Mohammad
    Commented Feb 2, 2014 at 15:59
  • \$\begingroup\$ I posted my answer just before the question was closed :) \$\endgroup\$
    – tomsmeding
    Commented Feb 2, 2014 at 17:36
  • \$\begingroup\$ Are you sure? I guess this is a bug with my browser then because at first I just saw the question flagged as a duplicate with 0 answers. And then after 30 min I saw the answer posted. \$\endgroup\$
    – Mohammad
    Commented Feb 2, 2014 at 17:39
  • \$\begingroup\$ I don't know. As far as I know, I posted the answer while there was stilll another bash answer and while the question wasn't yet closed. Anyway. \$\endgroup\$
    – tomsmeding
    Commented Feb 3, 2014 at 6:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.