My question is this:
I have a completed C program and now I want to print (display) the
current date for my intended users (i.e., the users have the option
for screen displays or a hard copy print out). Is there a way to
get the current date and time using the "date" command from the UNIX
shell? How do I execute this from within a C program?
Thanks a gazillion anyone!
The Don Mon
dw...@gte.com
SURE!
system("date");
would do it but you couldn't do anything with the output.
It would be THROWN onto the screen/stdout wherever your cursor was...
Now if you were to open a pipe() to the date command you could load it
into a character array, and do with it what you please:
FILE *pptr;
char Date[40];
pptr = popen("date", "r");
fgets(Date , (int)sizeof(Date) , pptr);
fprintf(stdout , "%s\n" , Date);
This is pretty messy programming, however. It's not a good idea to rely on
OS commands to run your program. To get the date (in a useable form for display,
etc..) check out the time.h library of functions:
localtime()
ctime()
in particular...
#include <time.h>
char *ptr; /* To hold your string */
time_t *clock; /* Standard "time" pointer */
/* First get the current time */
localtime(clock);
/* Then you convert that number to a "pretty" string,
pointed to by "ptr" */
ptr = ctime(clock);
/* And print it, or WHATEVER! */
or, make a little function...
char *Date()
{
time_t *clock;
localtime(clock);
return(ctime(clock));
}
You would call it by...
char *ptr;
ptr = Date();
Hope this helps out!
Howie
PS -> You can easily control the format of that date string using strftime()!
Check your manula pages for that one ;-)
---
#include <std_disclaimer.h> /***************************************
#define OPINIONS my_own * Howard K Michalski, ho...@fnma.COM *
* Fannie Mae Washington, DC, USA *
main(){for(;;);} ***************************************/
>[...] Is there a way to
>get the current date and time using the "date" command from the UNIX
>shell? How do I execute this from within a C program?
yes, use system("date");
NO. This is a lame solution.
Use the ctime(3) function, like so:
long ticks;
char *str;
ticks = time((char *)0);
str = ctime(&ticks);
printf("%s", str);
--
Arthur W. Neilson III | INET: a...@pilikia.pegasus.com
Bank of Hawaii Tech Support | UUCP: uunet!ucsd!nosc!pilikia!art
>In article <52...@ucsbcsl.ucsb.edu>
6500...@ucsbuxa.ucsb.edu (Michael P. Mack) writes:
>>In article <2...@ceylon.gte.com> dw...@harvey.gte.com (Donald W. Ottens) writes:>>
>>>[...] Is there a way to
>>>get the current date and time using the "date" command from the UNIX
>>>shell? How do I execute this from within a C program?
>>
>>yes, use system("date");
>NO. This is a lame solution.
I agree, but he asked specifically how to do it that way.
Mike Mack