gpt4 book ai didi

c - 如何在 printf(C 语言)中使用系统 ("date")?

转载 作者:行者123 更新时间:2023-11-30 18:51:56 24 4
gpt4 key购买 nike

我需要打印出这个:温度=“温度”@“日期/时间”,其中“日期/时间”是Linux“date”命令返回的日期和时间。

当我在程序中使用系统(“日期”)时,它会立即显示它。有没有办法避免这种情况发生?

这是我到目前为止的代码:

#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);
}
}

最佳答案

如果你想执行一个命令并获取它的输出,你需要使用popen(),通常你需要创建一个管道并重定向程序的输出,popen( ) 基本上不需要太多努力就可以为您做到这一点

#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;
}

关于c - 如何在 printf(C 语言)中使用系统 ("date")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com