Kyrol
Kyrol

Reputation: 3617

How to properly name different files created inside a function?

I know how to do it in general, but I have a particular situation.

I'm developing a function that saves certificate from TLS in a File. The arguments of the function are the certificate (as unsigned char *) and its length.

This function is called many times in very few time, so the main problem is to give a different name for every file created.

In the beginning I used the "time" to give different names

strftime(filename, sizeof(filename), "cert_%d-%m-%Y_%H:%M:%S.der", timeinfo);

but the problem is if two or more files are created in a period shorter than a second, the newest file overwritten the old one.

How can I properly solve this ? Any suggestion ? This is the 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;
  }

  // get the time
  time(&rawtime);
  timeinfo = localtime (&rawtime);

  // save every file with the time certificate was 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 to convert raw data (DER) to PEM certificate (good for parsing with openssl)
  i2d_X509_fp(fw, x_cert);

  // free cert e close file descriptor
  X509_free(x_cert);
  fclose(fw);
}

Upvotes: 0

Views: 79

Answers (1)

Kyrol
Kyrol

Reputation: 3617

As @Chris Turner suggest me on the comment, I used gettimeofday to keep the time for naming file (better for sorting by date).

This is the code I used to solve:

 gettimeofday(&tv, NULL);
  millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
  if(millisec>=1000) {                 // Allow for rounding up to nearest second
    millisec -=1000;
    tv.tv_sec++;
  }

  timeinfo = localtime(&tv.tv_sec);

  /* save every file with the time certificate was catched */
  strftime(filename, sizeof(filename), "cert_%Y-%m-%d_%H-%M-%S-%%03u.der", timeinfo);
  snprintf(buff, sizeof(buff), filename, tv.tv_usec);

Upvotes: 2

Related Questions