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

I want to put the output of the GNU / Linux date command into an array of characters.

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 result shows NULL in the array.

+4
source share
3 answers

Use popen to read the output of the command. Remember to close the stream with pclose .

 FILE *f = popen("date", "r"); fgets(array, sizeof(array), f); pclose(f); 

But instead of running an external program, you can use localtime and strftime .

 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 time zone.

 ctime_r(&t, array); 
+7
source

When you call system(command) , its return value is not char* for the output of the command, but the exit code of the command. The command completed successfully and returns 0 ; that is why you see NULL . If you want to get the string returned by the "date" command, you need to capture the output stream and convert it to a string.

+2
source
 #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); } 
+1
source

All Articles