4

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.

0

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1
#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t result;
    char array[25] = {'\0'};
    result = time(NULL);
    sprintf(array, "%s", asctime(localtime(&result)));
    printf("%s", array);
    return(0);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.