如何在c中将时间转换为ac字符串?

发布于 2024-09-15 02:13:20 字数 147 浏览 4 评论 0原文

我想在 .c 文件中的 .txt 文件中写入一些内容,但需要使用当前时间戳作为后缀来命名该文件,就像 filename_2010_08_19_20_30 一样。所以我得先定义文件名字符数组,然后自己处理文件名?一个一个分配字符?

有什么简单的方法可以做到这一点吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一生独一 2024-09-22 02:13:20

有一个名为 strftime 的函数,其存在的明确目的是将时间值写入人类可读的字符串。文档:http://linux.die.net/man/3/strftime

例子:

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

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;
}
疧_╮線 2024-09-22 02:13:20
  time_t timet;
  struct tm * timeinfo;
  char buffer [32];

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

  strftime(buffer,32,"_%Y_%m_%d_%H_%M",timeinfo);
  time_t timet;
  struct tm * timeinfo;
  char buffer [32];

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

  strftime(buffer,32,"_%Y_%m_%d_%H_%M",timeinfo);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文