Add date and time to a file name in c

strftime can be used to format the date an time :

#include <time.h>

char filename[40];
struct tm *timenow;

time_t now = time(NULL);
timenow = gmtime(&now);

strftime(filename, sizeof(filename), "/var/log/SA_TEST_%Y-%m-%d_%H:%M:%S", timenow);

fopen(filename,"w");

You can change the date an time format for whatever you want according to the strftime manual.

You can use the timestamp as 'compact format' with the result of time only.

sprintf(filename, "/var/log/SA_TEST_%d", (int)now);

/* ctime example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, time, ctime */

int main ()
{
  time_t rawtime;
  char buffer [255];

  time (&rawtime);
  sprintf(buffer,"/var/log/SA_TEST_%s",ctime(&rawtime) );
// Lets convert space to _ in

char *p = buffer;
for (; *p; ++p)
{
    if (*p == ' ')
          *p = '_';
}



  printf("%s",buffer);
  fopen(buffer,"w");

  return 0;
}

Output is

/var/log/SA_TEST_Wed_Jul_30_12:17:19_2014

  time_t rawtime;
  struct tm * timeinfo;
  char buffer [64];

  time (&rawtime);
  timeinfo = localtime (&rawtime);

  strftime (buffer,64,"/var/log/SA_TEST_%x_%X",timeinfo);//generate string SA_TEST_DATE_TIME
  fopen(buffer, "w");

Refer: man strftime for the formats you can get time and date in.

Tags:

C