Friday 12 February 2016

keeping log of program execution

Objective: Make a program that can be executed exactly three times and shows a message "Trial Version Expired.." if executed more then three times.
During the first three times it must show the name of the user, current date and time and date and time of previous executions.

Solution: It's pretty easy to work with if you can think of a way to store the count of execution somewhere which can be accesses even after program is not running. FILE is the solution, rest is easy. Store the counter of execution in a "status.txt: file and date and time of execution in "log.txt" and every time you execute the program read the content of these files and use it in the program and update these files.
File Handling has vast application in programming, the program shown below has one of the application in games for example storing High Score, you can try to implement this in this (game from my earlier post), storing state of a game when it was paused so as to restore it later and to maintain the log of execution etc.  


Note:
  • Take two files "log.txt" and "status.txt" in the same directory as that of the program.
  • Keep "log.txt" file empty while executing it for the first time.
  • Keep 1 in status.txt file. for the first execution and do not make changes in any file there after.
  • This code runs fine in Turbo C/C++. Dev CPP compiler gives an error date structure. 
  • After having executed it for more than 3 times, to re do the process make the "log.txt" file empty and again store 1 in "status.txt" file. 


#include<stdio.h>
#include<dos.h>
void main(){

     struct time t;  // to get time  from system
     struct date d; //  to get date of system
     int counter,temp,tem=0;  //to keep track of number of executions of program
     FILE *fi,*fo;
     clrscr();
     fi=fopen("status.txt","r");
     fscanf(fi,"%d",&counter);
     fclose(fi);
 printf("User: ShadowHack");
 getdate(&d);
 gettime(&t);
 printf("\nDate: ");
 printf("%d/%d/%d",d.da_day,d.da_mon,d.da_year);
 printf("\nTime: ");
 printf("%d:%d:%d",t.ti_hour,t.ti_min,t.ti_sec);

     if(counter==1){ // first time execution
     // already done above
     // no other requirements
     }
     else if(counter < 4){
  fo=fopen("log.txt","r");

  printf("\nPrevious login details:\n");
  while(!feof(fo)){
       // for formatting of date and time
      fscanf(fo,"%d",&temp);
      if(tem%3==0)
   printf("\n");
  tem++;
      printf("%d ",temp);

  }
  fclose(fo);

     }

     else{
 clrscr(); // to clear date and time printed above  // debug it later
 printf("Trial version Expired...");
     }
      fi=fopen("status.txt","w");
      fprintf(fi,"%d",++counter);

     fo=fopen("log.txt","a");
 fprintf(fo,"%d %d %d\n",d.da_day,d.da_mon,d.da_year);
 fprintf(fo,"%d %d %d\n",t.ti_hour,t.ti_min,t.ti_sec);
 fclose(fo);
 getch();

}

No comments:

Post a Comment