问题
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