Adding time and date to a filename - c

I'm trying to write a source file, that would take in the filename/directory and then add current date & time to the end of the file name. So far I've found out that we can use the time() & localtime() functions. However, I'm not quite sure on where to start.
Could someone give me some instructions/steps on the path I could follow to get there?
Thanks! :D

Use time() and localtime() to get the current time
Use strftime() to format it to the format you want.
Use snprintf() to combine the formatted time with the original file name.
Use rename() to do the actual renaming.
Note that all of the above can be done in one line of shell script, so ask yourself whether you really need to do it in C, as opposed to relegating it to sh.

To get the date/time you have to include time.h.
Then you can use the localtime function like this:
time_t t = time(NULL);
struct tm tm = *localtime(&t);
The struct tm contains the desired information. You can access the day of the month by tm.tm_mday and so on.
You can use sprintf to write all the date information to a string like this:
char datum[128];
sprintf(datum, "%d-%d-%dT%d:%d:%d", tm.tm_year+1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("%s\n", datum);
would give something like
2013-10-31T20:26:42
You can append this string to your filename by using strcat

This code will work.
char timestr[50];
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(timestr, sizeof(timestr)-1, "%m-%d-%Y", t);
timestr[49] = 0;
if((filename = malloc(strlen(argv[2])+strlen(timestr)+1) != NULL) {
filename[0] = '\0';
strcat(filename,argv[2];
strcat(filename,"_");
strcat(filename,timestr);
strcat(filename,".log");
}
Just change the argv[2] as per your code argc.

Related

What function in C can I use to get the date alone separate from time?

I am building a C program and I need to use time separately and also the date separately. I want to do this without using the structure struct tm since I have to send the time and the date to different columns in my database table called Logs:
int main(){
duration = clock() - duration;
double Duration = ((double)duration)/CLOCKS_PER_SEC;
char* IPaddr = inet_ntoa(newAddr.sin_addr);
int PortNo = ntohs(newAddr.sin_port);
printf("\n%s %s %d %f\n", task, IPaddr, PortNo, Duration);
printf("now: %d-%d-%d %d:%d:%d\n",tm.tm_mday,tm.tm_mon+1,tm.tm_year+1900,tm.tm_hour,tm.tm_min,tm.tm_sec);
if (mysql_query(con, "INSERT INTO Logs(ClientIP, ClientPort, Job_type, SubmissionTime, SubmissionDate, Duration)
VALUES(%s, %d, %s, %, %, %f)")) {
finish_with_error(con);
}
return 0;
}
You might want to declare two character arrays, one for the date string and one for the time string, and call strftime twice to construct them.
Something like this:
char SubmissionDate[20], SubmissionTime[20];
strftime(SubmissionDate, sizeof(SubmissionDate), "%Y-%m-%d", &tm);
strftime(SubmissionTime, sizeof(SubmissionTime), "%H:%M:%S", &tm);

Time doesn't update in C

I've encountered a very weird problem. My time isn't changing at all, and it's always printing the same time to log file. Here is a function that overwrites the last time, and should return the new one:
char * update_time(char *date)
{
time_t timer;
timer = time(&timer);
struct tm* time_real;
time_real = localtime(&timer);
date = asctime(time_real);
strftime(date, 26, "%Y.%m.%d %H:%M:%S", time_real);
return date;
}
Here is how i call the function to get new time:
date = update_time(date);
In main function i declare a pointer to char like this:
char *date = NULL;
and call the function everytime i need to get new data. What's more interesting is the fact, that when i debug my program line-by-line, i see that debugger "see" the new value of char *data, but it cannot be seen (printed) in the result file.
FIY here is the output txt file:
2015.04.16 20:09:49:09S Program starts
2015.04.16 20:09:49:09S Opening file: a.txt
2015.04.16 20:09:49:09S New data retrieved
2015.04.16 20:09:49:09S Closing file: a.txt
2015.04.16 20:09:49:09S End of program
Thanks for help in advance
EDIT
Gave my program a nap with Sleep(5000), and #nos and #Weather Vane were right, its all about elapsed time (what's more funny in the context of my question :D). We can close this ticket, thanks everyone for help.
Note: asctime is noted in a MSVC example to be deprecated since it uses an internal static array.
Consider using asctime_s instead, which takes a buffer argument for its output.
If you use asctime, you must copy its result before you use it again. It's no use remembering the returned pointer beyond its immediate use.
UPDATE
I can see a bug:
date = asctime(time_real); // overwrites the pointer you passed
trftimse(date, 26, "%Y.%m.%d %H:%M:%S", time_real); // passes the pointer provided by asctime
return date; // that's NOT the arg you passed
So the function uses the pointer to the static internal string returned by asctime, not the one you provided.
Your question shows this
char *date = NULL;
date = update_time(date);
So you are passing a NULL pointer to strftime. It worked before, because the irrelevant call to asctime replaced the NULL pointer with its internal static pointer.
But even when it's all correct, if the program runs and completes in a short time span, the granularity of time means that small time differences cannot be reported.

How tm structures (from time.h) works?

I need to create a struct where is set a date. I googled something and i found the tm structure from the library time.h, but I'm having some troubles;
I need to print some dates on a log file, here an example:
typedef struct tm* tm_;
...
void NEW_Job()
{
time_t t;
tm_ secs;
t=time(NULL);
secs=localtime(&t);
add_QUEUEnode(generate_job());
fprintf(f, "\n%d:%d.%d : New job created.", secs->tm_hour, secs->tm_min, secs->tm_sec);
}
I really don't know where i'm wrong.
Thanks in advance for the help :)
The exact error wasn't there, but in another line of the code, exactly here:
void PCunload(int b)
{
time_t t;
tm_ secs;
int hh, mm, ss;
hh=(time(NULL)-n[b].start_time)/3600;
mm=((time(NULL)-n[b].start_time)%3600)/60;
ss=((time(NULL)-n[b].start_time)%3600)%60;
t=time(NULL);
secs=localtime(&t);
n[b].job.priority=-1;
-->>fprintf(f, "\n%d:%d.%d : PC number %d unloaded; elapsed time: %d:%d.%d", secs->tm_hour, secs->tm_min, secs->tm_sec, hh, mm, ss);
}
There I tried to do the conversion inside the printf functions, but something goes wrong...
My apologies!
strftime() can help you printing date and time at your favorite format. Please take a look at man strftime.

c time formattings

How do I format a time_t structure to something like this year-month-day h:m:s,
I have already tried using ctime:
time_t t = time((time_t*) NULL);
char *t_format = ctime(&t);
but it doesn't give me the desired results
example :
2011-11-10 10:25:03. What I need is a string containing the result so I can write it to a file. Thanks
Use strftime from time.h like so:
char tc[256];
strftime(tc, 256, "%Y-%m-%d %H:%M:%S", tm);
http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html

C - putting current date in a filename

I have 4 values: A,B,C,D. After doing a set of computations with those values, I want my code to output the results in a file of the form ABCD_MM.DD.YY.txt, to keep track of when it was done.
I'm not quite sure on the best way to do this in C. I have a "working" version using itoa(), which isn't a standard C function and will go (and has gone) unrecognized on machines other than mine when compiling.
This is the code I have for doing this, could someone help with a better (and universally accepted) way? The char array name was defined with a global scope.
void setFileName(){
time_t now;
struct tm *today;
char date[9];
//get current date
time(&now);
today = localtime(&now);
//print it in DD.MM.YY format.
strftime(date, 15, "%d.%m.%Y", today);
char buff[20];
char vars[20];
//put together a string of the form:
//"ABCD_DD.MM.YY.txt"
strcpy(vars, itoa(A, buff, 20));
strcat(vars, itoa(B, buff, 20));
strcat(vars, itoa(C, buff, 20));
strcat(vars, itoa(D, buff, 20));
strcpy(name, vars);
strcat(name, "_");
strcat(name, date);
strcat(name, ".txt");
}
char filename [ FILENAME_MAX ];
snprintf(filename, FILENAME_MAX, "%d%d%d%d_%s.txt", A, B, C, D, date);

Resources