Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the output of `date` command in a char array?

Tags:

c

linux

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.

like image 997
Sandeep Singh Avatar asked Jan 17 '23 01:01

Sandeep Singh


2 Answers

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, &lt);
strftime(array, sizeof(array), "%a %b %d &T %z %Y", &lt);

ctime is similar, but does not include the timezone.

ctime_r(&t, array);
like image 163
jxh Avatar answered Jan 29 '23 19:01

jxh


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.

like image 30
Sergey Kalinichenko Avatar answered Jan 29 '23 19:01

Sergey Kalinichenko