how to get minute of the system time from C program - c

how to get minute of the system time from C program? can I use gettimeoftheday?? If anyone has C program which can do this please share, I'm a newbie.Thanks
some sample code
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
return 0;
}

You can use strftime to get only the minutes part :
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[0x100];
time_t curtime;
// Don't forget to check the return value !
curtime = time(NULL);
if (curtime == -1)
{
perror("time()");
return 1;
}
strftime(buffer,0x100,"%M",localtime(&curtime));
printf("minutes: %s\n", buffer);
return 0;
}
No need to use gettimeofday here, use it only if you want a precision better than seconds.

#include <stdio.h>
#include <time.h>
int main()
{
time_t curtime;
char buffer[30];
struct tm* tm_info;
time(&curtime);
tm_info = localtime(&curtime);
strftime(buffer, 30, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
%Y:- will print year
%m:- will print Month
%d:- will print day
%H:- will print Hour
%M:- will print Minute
%S:- will print Second

Related

C ISO 8601 time with microseconds windows

I am trying to format my time stamp in ISO 8601 with microseconds in C.
Like this 2014-11-06T10:34:47.123456Z, but I cant seem to get microseconds.
Any help would be greatful.
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNING
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#define SIZE 256
int
main(void)
{
char buffer[SIZE];
time_t curtime;
/* Get the current time. */
curtime = time(NULL);
strftime(buffer, sizeof buffer, "ISO 8601 %Y-%m-%dT%H:%M:%S\n", gmtime(&curtime));
fputs(buffer, stdout);
getchar();
return 0;
}

Implement overlay in terminal

I want to create an overlay in terminal
This Q&D shows the time in right/bottom
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <termios.h>
#include <error.h>
#include <unistd.h>
#include <time.h>
static char termbuf[2048];
int main()
{
char *termtype = getenv("TERM");
time_t timer;
char buffer[26];
struct tm* tm_info;
if (tgetent(termbuf, termtype) < 0) {
error(EXIT_FAILURE, 0, "Could not access the termcap data base.\n");
return 1;
}
int lines = tgetnum("li");
int columns = tgetnum("co");
int pos=1;
while (1) {
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
printf("\033[s");
fflush(stdout);
printf("\033[%d;%dH%s\n", lines - 2, columns - 20, buffer);
printf("\033[u");
sleep(1);
}
return 0;
}
it is compiled with:
$ gcc time-overlay.c -ltermcap -o time-overlay
And to use it:
$ ./time-overlay &
It will show:
2017-04-29 12:29:15
And keep updating time.
To stop:
$ fg
Ctrl+C
But, is there a better way to do that with some library that abstracts low level calls (like save restore cursor position or print in some line/col)
I want to keep existing terminal output (so curses with initscr() will not work)
This is how you would use termcap (or anything provides a termcap interface, e.g., ncurses):
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define MAXTERM 2048
#define EndOf(s) (s) + strlen(s)
int
main(void)
{
char termbuf[MAXTERM];
char workbuf[MAXTERM];
char *working = workbuf;
int lines, columns;
char *save_cursor, *move_cursor, *restore_cursor;
if (tgetent(termbuf, getenv("TERM")) < 0) {
fprintf(stderr, "Could not access the termcap database.\n");
return EXIT_FAILURE;
}
lines = tgetnum("li");
columns = tgetnum("co");
save_cursor = tgetstr("sc", &working);
move_cursor = tgetstr("cm", &working);
restore_cursor = tgetstr("rc", &working);
while (1) {
time_t timer;
char buffer[1024];
struct tm *tm_info;
time(&timer);
tm_info = localtime(&timer);
strcpy(buffer, save_cursor);
sprintf(EndOf(buffer), tgoto(move_cursor, columns - 20, lines - 2));
strftime(EndOf(buffer), 26, "%Y-%m-%d %H:%M:%S", tm_info);
strcat(buffer, restore_cursor);
write(fileno(stderr), buffer, strlen(buffer));
sleep(1);
}
return EXIT_SUCCESS;
}
It could still be improved since the various strings returned from tgetstr are not guaranteed to be provided by all terminal descriptions, and of course, termcap applications always have buffer-overflow issues to work around.

Compare two times in C

How do I compare time in C?
My program is getting the last modified time of 2 files, then compare that time to see which time is the latest.
Is there a function that compares time for you, or you have to create one yourself? This is my get time function:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
void getFileCreationTime(char *path) {
struct stat attr;
stat(path, &attr);
printf("Last modified time: %s", ctime(&attr.st_mtime));
}
Use difftime(time1, time0) from time.h to get the difference between two times. This calculates time1 - time0 and returns a double representing the difference in seconds. If it's positive, then time1 is later than time0; if negative, time0 is later; if 0, they're the same.
You can compare two time_t values to find which is newer:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
static time_t getFileModifiedTime(const char *path)
{
struct stat attr;
if (stat(path, &attr) == 0)
{
printf("%s: last modified time: %s", path, ctime(&attr.st_mtime));
return attr.st_mtime;
}
return 0;
}
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s file1 file2\n", argv[0]);
return 1;
}
time_t t1 = getFileModifiedTime(argv[1]);
time_t t2 = getFileModifiedTime(argv[2]);
if (t1 < t2)
printf("%s is older than %s\n", argv[1], argv[2]);
else if (t1 > t2)
printf("%s is newer than %s\n", argv[1], argv[2]);
else
printf("%s is the same age as %s\n", argv[1], argv[2]);
return 0;
}
If you want to know the difference between the values in seconds, then you need to use difftime() officially, but in practice you can simply subtract the two time_t values.
You can use below method
double difftime (time_t end, time_t beginning);
It returns the time difference in seconds. You can find example here.
my code:
char * findLeastFile(char *file1, char *file2){
struct stat attr1, attr2;
if (stat(file1, &attr1) != 0 || stat(file2, &attr2) != 0)
{
printf("file excetion");
return NULL;
}
if(difftime(attr1.st_mtime,attr2.st_mtime) >= 0)
return file1;
else
return file2;
}

clock using fflush is not clearing screen

I am trying to make a clock in C, but the screen is not properly clearing, it just keeps printing to a new line. How am I improperly using fflush?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
while (1) {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("%s", asctime (timeinfo));
fflush(stdout);
}
return 0;
}
This strips out the newline from the asctime string and then uses a return to push the cursor back to the start of line
#include <string.h>
int main()
{
while (1) {
time_t rawtime;
char st[30];
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf (st,"%s", asctime (timeinfo));
*(index(st,'\n'))='\0';
printf("\r%s",st);
flush(stdout);
sleep(1);
}
return 0;
}
This one has the advantage that it will work from the current location on the screen, no matter what that is. I added a label to print "The time is: " in order to show this. It does this by back spacing from the end of the time string rather than going to an absolute screen position or column. Caveat: The hack to get sleep() under Visual C has not been tried.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#define sleep(T) Sleep((T) * 1000)
#else
#include <unistd.h>
#endif
int main(void)
{
char buf[42];
time_t the_time[1];
int i, len;
printf("The time is: ");
for (;;) {
time(the_time);
len = strlen(strcpy(buf, asctime(localtime(the_time)))) - 1;
printf("%.*s", len, buf);
for (i = 0; i < len; i++) putchar('\b');
fflush(stdout);
sleep(1);
}
return 0;
}
This will do it... (uses an evil windows call SetConsoleCursorPosition(), but does the trick)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gotoxy(int x, int y);
int main()
{
while (1) {
time_t rawtime;
struct tm * timeinfo;
gotoxy(0,0);//set to the upper left hand corner
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("%s", asctime (timeinfo));
fflush(stdout);
}
return 0;
}
void gotoxy(int x, int y)
{
COORD pos = {x, y};
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}
Try this for POSIX:
#!/usr/bin/tcc -run
#include <stdio.h>
#include <termios.h>
int main ()
{
struct termios ts0, ts1;
char cls [FILENAME_MAX];
FILE *f;
f = popen ("tput clear", "r");
fgets (cls, FILENAME_MAX, f);
pclose (f);
tcgetattr (0, &ts0);
ts1 = ts0;
ts1.c_lflag &= ~ECHO;
ts1.c_lflag &= ~ICANON;
tcsetattr (0, TCSAFLUSH, &ts1);
fputs (cls, stdout);
while (1) putchar (getchar ());
tcsetattr (0, TCSAFLUSH, &ts0);
return 0;
}

time() in C language

I have tried the function:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);
printf ("%ld hours since January 1, 1970", seconds/3600);
return 0;
}
It is useful but it returns the time in number of seconds since 1970. In my case, I would like to obtain a result with more precision, to distinguish two events happening in the same second. Is it possible to do that?
Use gettimeofday(3). It allows you to get the time in microseconds.
#include <stdio.h>
#include <sys/time.h>
int main(int argc, char **argv)
{
struct timeval tv = { 0 };
gettimeofday(&tv, NULL);
printf("sec: %ld usec: %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
or with clock_gettime():
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
struct timespec ts = { 0 };
clock_gettime(CLOCK_REALTIME, &ts);
printf("sec: %ld nsec: %ld\n", ts.tv_sec, ts.tv_nsec);
return 0;
}
Try clock_gettime . It gives additional info in nanoseconds.
Basic Standard C does not describe any calendar time functions with a resolution better than 1 second.
You have to use extensions.
For POSIX, try gettimeofday() (obsolescent) clock_gettime().
For Windows, apparently, you can use GetSystemTime().

Resources