00001 #include <stdio.h>
00002 #include <time.h>
00003 #include <unistd.h>
00004 #include <stdlib.h>
00005 #include <string.h>
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 void static getlock(FILE *fp, char *fname)
00019 {
00020 int sleeps;
00021 for(sleeps=0; lockf(fileno(fp),F_TLOCK,0); sleeps++)
00022 {
00023 if (sleeps >= 20)
00024 {
00025 fprintf(stderr,"Lock stuck on %s, GetNextID failed.\n", fname);
00026 exit(1);
00027 }
00028 sleep(1);
00029 }
00030 return;
00031 }
00032
00033 int main(int argc, char **argv)
00034 {
00035 char fname[1024];
00036 int NextIDsn;
00037 int nread;
00038 int old_date, new_date;
00039 int year, month, day;
00040 char fixedpart[100];
00041 char NextID[100];
00042 FILE *fp;
00043 struct tm *now;
00044 time_t nowtime;
00045
00046 if (argc < 2)
00047 {
00048 fprintf(stderr, "GetNextID failed, needs filename.\n");
00049 exit(1);
00050 }
00051 strncpy(fname, argv[1], 1000);
00052
00053 if (argc == 3)
00054 {
00055 strcpy(fixedpart, argv[2]);
00056 NextIDsn = 0;
00057 old_date = 0;
00058 fp = fopen(fname, "w");
00059 getlock(fp, fname);
00060 }
00061 else
00062 {
00063 fp = fopen(fname, "r+");
00064 if (!fp)
00065 {
00066 fprintf(stderr, "GetNextID failed to open sn file, %s.\n", fname);
00067 exit(1);
00068 }
00069 getlock(fp, fname);
00070
00071 nread = fscanf(fp,"%[^-]-%d-%d",fixedpart,&old_date,&NextIDsn);
00072 if (nread != 3)
00073 {
00074 fprintf(stderr,"GetNextID failed. found %d instead of 3 fields in %s\n", nread, fname);
00075 exit(1);
00076 }
00077 }
00078
00079 nowtime = time(0);
00080 now = gmtime(&nowtime);
00081 new_date = 10000*(now->tm_year+1900) + 100*(now->tm_mon+1) + now->tm_mday;
00082 if (old_date != new_date)
00083 {
00084 FILE *history;
00085 strcat(fname, ".history");
00086 history = fopen(fname, "a");
00087 fprintf(history,"%s-%d-%05d\n", fixedpart, old_date, NextIDsn);
00088 fclose(history);
00089 NextIDsn = 1;
00090 }
00091 else
00092 NextIDsn += 1;
00093 rewind(fp);
00094 sprintf(NextID,"%s-%d-%05d", fixedpart, new_date, NextIDsn);
00095
00096 fprintf(fp,"%s\n",NextID);
00097 rewind(fp);
00098 lockf(fileno(fp),F_ULOCK,0);
00099 fclose(fp);
00100 printf("%s\n",NextID);
00101 }