繁体   English   中英

如何在 C 中执行终端命令?

[英]How to execute a terminal command in C?

我正在 C 中编写程序。 我想以 H:M:S:3N 的形式获取当前的小时、分钟、秒和纳秒。 基本上。 echo "$(date +' %H:%M:%S:%3N')"命令做我想要的。 如何在我的 C 代码中执行它并打印结果?

任何帮助表示赞赏!

您正在寻找strftime 例如:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int
main(int argc, char **argv)
{
    int rv = EXIT_SUCCESS;
    struct timeval tv;
    struct tm *tm;
    char *default_args[] = { "%H:%M:%S %B %d, %Y", NULL };
    if( gettimeofday(&tv, NULL) == -1 ){
        perror("gettimeofday");
        exit(1);
    }
    argv = argc < 2 ? default_args : argv + 1;
    tm = gmtime(&tv.tv_sec);
    for( ; *argv; argv += 1 ){
        char buf[1024];
        const char *fmt = *argv;
        if( strftime(buf, sizeof buf, fmt, tm) ){
            printf("%s\n", buf);
        } else {
            fprintf(stderr, "Error formatting %s\n", fmt);
            rv = EXIT_FAILURE;
        }
    }
    return rv;
}

请注意, strftime通常不支持%N ,因此您必须手动解析纳秒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM