views:

63

answers:

3

Hi, I wanna to write something to a .txt file in .c file, but required to name that file with the current timestamp as the postfix, just like filename_2010_08_19_20_30. So I have to define the filename char array first and process the filename by myself?Assign the character one by one?

Is there any easy way to do that?

+9  A: 

There's a function called strftime that exists for the express purpose of writing a time value into a human-readable string. Documentation: http://linux.die.net/man/3/strftime

An example:

#include <time.h>
#include <stdio.h>

int main()
{
   FILE* file;
   char filename[128];
   time_t now;
   struct tm tm_now;

   now = time(NULL);
   localtime_r(&now, &tm_now);

   strftime(filename, sizeof(filename), "filename_%Y_%m_%d_%H_%M.txt", &tm_now);

   file = fopen(filename, "w");

   fprintf(file, "Hello, World!\n");

   fclose(file);

   return 0;
}
Tyler McHenry
+1  A: 

Check out the strftime function:

http://www.cplusplus.com/reference/clibrary/ctime/strftime/

Starkey
+2  A: 
  time_t timet;
  struct tm * timeinfo;
  char buffer [32];

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

  strftime(buffer,32,"_%Y_%m_%d_%H_%M",timeinfo);
Harry Caulk