c - How to properly name different files created inside a function? -


i know how in general, have particular situation.

i'm developing function saves certificate tls in file. arguments of function certificate (as unsigned char *) , length.

this function called many times in few time, main problem give different name every file created.

in beginning used "time" give different names

strftime(filename, sizeof(filename), "cert_%d-%m-%y_%h:%m:%s.der", timeinfo);

but problem if 2 or more files created in period shorter second, newest file overwritten old one.

how can solve ? suggestion ? function code:

static void save_certificate_file(const unsigned char * cert, u_int16_t cert_len) {   file *fw;   x509 *x_cert;   char filename[cert_len];   struct tm *timeinfo;   time_t rawtime;    x_cert = d2i_x509(null, &cert, cert_len);   if (!x_cert) {     fprintf(stderr, "error on d21_x509 funtion\n");     return;   }    // time   time(&rawtime);   timeinfo = localtime (&rawtime);    // save every file time certificate catched   strftime(filename, sizeof(filename), "cert_%d-%m-%y_%h:%m:%s.der", timeinfo);    if(!(fw = fopen(filename,"w"))) {     fprintf(stderr, "error on opening file descriptor fw\n");     return;   }   // function convert raw data (der) pem certificate (good parsing openssl)   i2d_x509_fp(fw, x_cert);    // free cert e close file descriptor   x509_free(x_cert);   fclose(fw); } 

as @chris turner suggest me on comment, used gettimeofday keep time naming file (better sorting date).

this code used solve:

 gettimeofday(&tv, null);   millisec = lrint(tv.tv_usec/1000.0); // round nearest millisec   if(millisec>=1000) {                 // allow rounding nearest second     millisec -=1000;     tv.tv_sec++;   }    timeinfo = localtime(&tv.tv_sec);    /* save every file time certificate catched */   strftime(filename, sizeof(filename), "cert_%y-%m-%d_%h-%m-%s-%%03u.der", timeinfo);   snprintf(buff, sizeof(buff), filename, tv.tv_usec); 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -