How to convert the time to a c string in c?

那年仲夏 提交于 2019-12-12 15:31:04

问题


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?


回答1:


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;
}



回答2:


  time_t timet;
  struct tm * timeinfo;
  char buffer [32];

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

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



回答3:


Check out the strftime function:

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



来源:https://stackoverflow.com/questions/3522480/how-to-convert-the-time-to-a-c-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!