-1

I need to print out this: Temperature = "temperature" @ "date/time", where "date/time" is the date and time as returned by the Linux 'date' command.

When I use system("date") in my program it displays it immediately. Is there a way to keep this from happening?

This is my code so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#define FREQUENCY 5
#define MIN -10
#define MAX 35

int main()
{
    time_t t;

    /*
    * Initialize random number generator
    */
    srand((unsigned) time(&t));

    /*
    * Print random values between -10 and +35°C
    */
    while(1)
    {
            double random = ((double)rand() * (MAX-MIN))/(double)RAND_MAX+MIN;
            printf("Temperature = %1.2f @ %d\n", random, system("date"));
            fflush(stdout);
            sleep(FREQUENCY);
    }
}
Yannick Maris
  • 329
  • 1
  • 4
  • 16

1 Answers1

2

You need to use popen() if you want to execute a command and grab it's output, in general you need to create a pipe and redirect the output of the program, popen() basically does that for you without much effort just

#include <stdio.h>

int
main(void)
{
    FILE *pipe;
    char buffer[100];

    pipe = popen("date", "r");
    if (pipe == NULL)
        return -1;
    while (fgets(buffer, sizeof(buffer), pipe) != NULL)
        fprintf(stdout, "%s", buffer);
    pclose(pipe);
    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97