How tm structures (from time.h) works? - c

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.

Related

fprintf starts printing with strange characters then proceeds to print normally

I have run into a problem when trying to write to file using fprintf(). When I start writing into file the first few lines are composed of semi-random invalid characters and after that the rest is printed normally. I have no idea what can cause the problem. Below is the code that produces the problem.
functions called:
double calc_time(clock_t s, clock_t e){
return ((double)(e-s) / (sysconf(_SC_CLK_TCK)));
}
void print_times(FILE *f, char *operation, clock_t s, clock_t e, struct tms *st, struct tms *et){
printf("%s", operation);
printf("\nREAL TIME: %f\n", calc_time(s,e));
printf("USER TIME: %f\n", calc_time(st->tms_utime,et->tms_utime));
printf("SYS TIME: %f\n", calc_time(st->tms_stime,et->tms_stime));
printf("HERE");
fprintf(f,"%s", operation);
fprintf(f,"\nREAL TIME: %fl", calc_time(s,e));
fprintf(f,"\nUSER TIME: %fl", calc_time(st->tms_utime,et->tms_utime));
fprintf(f,"\nSYS TIME: %fl", calc_time(st->tms_stime,et->tms_stime));
}
and the printing takes place here:
f = fopen("raport2.txt","a");
clock_t r_times[2];
struct tms* t_times[2];
t_times[0] = calloc(1,sizeof(struct tms));
t_times[1] = calloc(1,sizeof(struct tms));
r_times[0] = times(t_times[0]);
struct block_array* array = create(4);
r_times[1] = times(t_times[1]);
print_times(f, "\nCreating array", r_times[0], r_times[1], t_times[0], t_times[1]);
r_times[0] = times(t_times[0]);
struct file_sequence seq = seq_def("t1.txt t2.txt b1.txt b2.txt");
char *tmp = compare(seq);
create_blocks(array,tmp,4);
r_times[1] = times(t_times[1]);
print_times(f,"\nCreating blocks",r_times[0],r_times[1],t_times[0],t_times[1]);
r_times[0] = times(t_times[0]);
delete_block(array,1);
delete_block(array,2);
delete_block(array,3);
delete_block(array,4);
r_times[1] = times(t_times[1]);
print_times(f, "\nDeleting blocks", r_times[0], r_times[1], t_times[0], t_times[1]);
The error was caused by a different part of code than provided in the snippets (although the github source will still reproduce it). It turns out that in a different part of program I was writing to a file without erasing it's previous contents (I thought that touch does that), then data retrieved from the file was causing memory leaks and all kinds allocation problems.
Use %lf to print doubles, rather than the typo %fl you're using.

Adding time and date to a filename

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.

asctime time output error

#include<time.h>
#include<stdio.h>
int main(void)
{
time_t timer;
int i;
char mon[4];
char *ti=0;
ti=asctime(localtime(&timer));
ti=ti+4;
for(i=0;i<3;i++)
{
mon[i]=*ti++;
}
mon[3]='\0';
timer=time(NULL);
printf("The current time is %s\n",mon);
return 0;
}
Hi, Can anyone expalin why asctime returns wrong time-pointer sometimes.Iam using 'mon' to store the month from asctime string and when printing it on the console,it displays sometimes 'Mar' and sometimes some other month.
You are using timer without initializing it. Before calling localtime, try:
time(&timer);
Also, a simpler way to do it would be:
ctime(&timer);

can't get C method icalrecur_expand_recurrence to work

This is a bit frustrating. I've been working on this for a while now, and I can't seem to get this method to work like it says it does.
#include "icalrecur.h"
#include <time.h> /* for time() */
#include <stdio.h>
int get_occurrences(char* rrule, time_t start, int count)
{
//char* rule; /* rule string */
// *rule = PG_GETARG_CHAR(0);
time_t *result[count]; /* output array */
icalrecur_expand_recurrence(rrule, start, count, *result);
return (time_t) *result;
}
//time_t *output[5*8];
void main() {
time_t right_now = time(0);
char *_rrule = "FREQ=WEEKLY;INTERVAL=2;COUNT=8;WKST=SU;BYDAY=TU,TH";
get_occurrences(_rrule, right_now, 5);
}
I save this test file as ical_recur.h. Then I type in bash:
gcc -I/usr/local/libical/include/libical -L/usr/local/libical/lib/ -lical -o hello ical_recur.c
To include the libical.a libraries. The include/libical directory has icalrecur.h in it, so I really don't even need to be including the whole ical library.
~: ./hello
Segmentation fault
Anytime I change around any pointers, it starts complaining about something during compilation. Can anyone get this to work?? Source files are from Marketcircle on github.
Looking at the documentation it seems that you have an unwanted extra level of indirection - you need to change:
time_t *result[count]; /* output array */
icalrecur_expand_recurrence(rrule, start, count, *result);
to:
time_t result[count]; /* output array */
icalrecur_expand_recurrence(rrule, start, count, result);
Also you're passing a read-only string literal to a function which expects a char * - this should at least give you a compiler warning (hint: always use gcc -Wall ..., read the warnings carefully, understand them and fix them). main() should look more like this:
int main() {
time_t right_now = time(0);
char _rrule[] = "FREQ=WEEKLY;INTERVAL=2;COUNT=8;WKST=SU;BYDAY=TU,TH";
get_occurrences(_rrule, right_now, 5);
return 0;
}
Some more problems:
this line doesn't do anything useful, but it's not clear what you're trying to achieve:
char _size = (char)(((int)'0') + sizeof(result));
all those casts are a "code smell" and this should tell you that you're doing something very wrong here
your function is defined as returning an int, but you're trying to cast your array to a time_t and return that, which also makes no sense - again, turn on compiler warnings - let the compiler help you find and fix your mistakes.
Now you can use this extension for postgresql.
Example usage:
SELECT * FROM
unnest(
rrule_get_occurrences('FREQ=WEEKLY;INTERVAL=1;WKST=MO;UNTIL=20200101T045102Z;BYDAY=SA;BYHOUR=10;BYMINUTE=51;BYSECOND=2'::rrule,
'2019-12-07 10:51:02+00'::timestamp with time zone)
);
unnest
------------------------
2019-12-07 10:51:02+00
2019-12-14 10:51:02+00
2019-12-21 10:51:02+00
2019-12-28 10:51:02+00
(4 rows)

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

Resources