如何建立与当前时间命名的文件? [英] how to create files named with current time?

查看:113
本文介绍了如何建立与当前时间命名的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建日志目录下的一系列文件的哪些命名基于执行时间每个文件。而在每一个文件,我想保存我的程序,如函数原型行为等一些日志信息。
通常我使用的fopen硬盘的方式(登录/ ***,A),这是不是这个purpose.And我只写一个时间戳功能:

I want to create a series of files under "log" directory which every file named based on execution time. And in each of these files, I want to store some log info for my program like the function prototype that acts,etc. Usually I use the hard way of fopen("log/***","a") which is not for this purpose.And I just write a timestamp function:

char* timeStamp(char* txt){
  char* rc;
  char timestamp[16];
  time_t rawtime = time(0);
  tm *now = localtime(&rawtime);

  if(rawtime != -1) {
     strftime(timestamp,16,"%y%m%d_%H%M%S",now);
     rc = strcat(txt,timestamp);
  }
  return(rc);
}

但我不知道下一步该怎么做。请帮我这个!

But I don't know what to do next. Please help me with this!

推荐答案

声明一个字符阵列大足以容纳16 + 登录/ (所以20个字符总数),并把它初始化为登录/然后用的strcat()或东西要添加您的功能恢复阵列的结束时间字符串相关的。还有你去!

Declare a char array big enough to hold 16 + "log/" (so 20 characters total) and initialize it to "log/", then use strcat() or something related to add the time string returned by your function to the end of your array. And there you go!

请注意字符串除了是如何工作的:你的字符阵列为16个字符,这意味着你可以把15个字符的加上一个NULL字节的。不要忘记,这是非常重要的。如果你需要一个16字符的字符串,则需要将其声明为字符时间戳[17] 来代替。需要注意的是登录/是一个4个字符的字符串,所以它占用了5个字符(一个用于末尾的NUL字节),但的strcat ()将覆盖的开始的结尾的NUL字节,所以你会用正确的数字结束。不计算NUL终止的两倍,但更重要的是,不要忘记它。调试这是一个更大的问题。

Note how the string addition works: Your char array is 16 characters, which means you can put in 15 characters plus a nul byte. It's important not to forget that. If you need a 16 character string, you need to declare it as char timestamp[17] instead. Note that "log/" is a 4 character string, so it takes up 5 characters (one for the nul byte at the end), but strcat() will overwrite starting at the nul byte at the end, so you'll end up with the right number. Don't count the nul terminator twice, but more importantly, don't forget about it. Debugging that is a much bigger problem.

编辑:虽然我们在这,我误解你的code。我以为它只是返回的字符串的时候,但现在看来,它增加了时间传入的字符串。这可能比我还以为你做的更好。不过,如果你愿意,你可以只是使函数做所有的工作 - 它把日志/字符串中,它把时间戳之前。这并不难。

While we're at it, I misread your code. I thought it just returned a string with the time, but it appears that it adds the time to a string passed in. This is probably better than what I thought you were doing. However, if you wanted, you could just make the function do all the work - it puts "log/" in the string before it puts the timestamp. It's not that hard.

这篇关于如何建立与当前时间命名的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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