如何将时间转换为C A C字符串? [英] How to convert the time to a c string in c?

查看:124
本文介绍了如何将时间转换为C A C字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写点东西在.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?

推荐答案

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

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

一个例子:

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

这篇关于如何将时间转换为C A C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆