Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add date and time to a file name in c

Tags:

c

Im looking for a way to add the current date and time to a log file im opening for now im using :

fopen("/var/log/SA_TEST","w");

How to make it

fopen("/var/log/SA_TEST_DATE_AND_TIME","w");

Thx a lot (In c)

like image 868
JohnnyF Avatar asked Jul 30 '14 06:07

JohnnyF


People also ask

How do you insert date and time in FileName?

I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.

How do you write the date in a file name?

To provide a description in the name itself of the file contents, you should include elements such as: a date, or at least the year, when the contents of the file were created, in the YYYY-MM-DD format (four digit year, two digit month, two digit day, with a dash in between.)

How do I save a file name as a time?

In the workbook you need to name it by current timestamp, please press the Alt + F11 keys simultaneously to open the Microsoft Visual Basic for Applications window. 3. Press the F5 key to run the code. Then a Save As dialog box pops up, you can see the timestamp displaying in the File name box.


1 Answers

strftime can be used to format the date an time :

#include <time.h>

char filename[40];
struct tm *timenow;

time_t now = time(NULL);
timenow = gmtime(&now);

strftime(filename, sizeof(filename), "/var/log/SA_TEST_%Y-%m-%d_%H:%M:%S", timenow);

fopen(filename,"w");

You can change the date an time format for whatever you want according to the strftime manual.

You can use the timestamp as 'compact format' with the result of time only.

sprintf(filename, "/var/log/SA_TEST_%d", (int)now);
like image 156
Ek1noX Avatar answered Nov 07 '22 06:11

Ek1noX