linux c 日期作为 文件名程序代码

本文介绍了一种在Linux环境下利用当前时间生成带有日期的文件名的方法。通过使用time()函数获取当前时间,并结合strftime()函数将时间格式化为字符串,最终形成如result_2022-11-18_14-30-26.csv这样的文件名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

linux c 日期作为 文件名程序代码

    time_t t = time(0);
    struct tm *tmp = localtime(&t);
    char time_str[64] = {0};
    strftime(time_str, sizeof(time_str), "%F_%H-%M-%S", tmp);

代码2

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

int Amain() {
  time_t t = time(0);
  struct tm *tmp = localtime(&t);
  char time_str[64] = {0};
  strftime(time_str, sizeof(time_str), "%F_%H-%M-%S", tmp);

  char filename[128] = {0};
  sprintf(filename, "%s%s%s", "result_", time_str, ".csv");
  printf("filename: %s\n", filename);
}


int Bmain()
{
   char ct[80];
   time_t  tt;
   struct tm *tblock;

   tt = time(NULL);
   tblock = localtime(&tt);

   printf("Local time is %s\n", asctime(tblock));

   strftime(ct, sizeof(ct), "%Y-%m-%d %H:%M:%S", tblock);
   printf("now is %s\n", ct);

   return 0;
}

int main()
{
    Amain();
    Bmain();

    return 0 ;
}

执行结果:

filename: result_2022-11-18_14-30-26.csv
Local time is Fri Nov 18 14:30:26 2022

now is 2022-11-18 14:30:26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值