How to convert time to string c to c?

I want to write something to a .txt file in a .c file, but in order to name this file with the current timestamp as a postfix, just like filename_2010_08_19_20_30. So, first you need to define an array of char names and process the file name yourself. Assign a character one at a time?

Is there an easy way to do this?

+3
source share
3 answers

There is a function called strftimethat exists with the explicit purpose of writing the time value to a readable string. Documentation: http://linux.die.net/man/3/strftime

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;
}
+9
source
  time_t timet;
  struct tm * timeinfo;
  char buffer [32];

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

  strftime(buffer,32,"_%Y_%m_%d_%H_%M",timeinfo);
+2
source

Source: https://habr.com/ru/post/1760546/


All Articles