I want to put the output of GNU/Linux date
command in a character array.
Example:
char array[25];
$ date
Thu Jul 19 09:21:31 IST 2012
printf("%s", array);
/* Should display "Thu Jul 19 09:21:31 IST 2012" */
I tried this:
#include <stdio.h>
#include <string.h>
#define SIZE 50
int main()
{
char array[SIZE];
sprintf(array, "%s", system("date"));
printf("\nGot this: %s\n", array);
return 0;
}
But the output shows NULL
in the array.
Use popen
to be able to read the output of a command. Make sure to close the stream with pclose
.
FILE *f = popen("date", "r");
fgets(array, sizeof(array), f);
pclose(f);
But, you could use localtime
and strftime
instead of executing an external program.
time_t t = time(0);
struct tm lt;
localtime_r(&t, <);
strftime(array, sizeof(array), "%a %b %d &T %z %Y", <);
ctime
is similar, but does not include the timezone.
ctime_r(&t, array);
When you call system(command)
, its return value is not a char*
to the command's output, but an exit code of the command. The command completes successfully, and returns 0
; that's why you see a NULL
. If you would like to fetch the string returned by the "date"
command, you need to capture the output stream and convert it to a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With