You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何执行终端命令获取H:M:S:3N格式时间并打印

实现方案

方法1:直接调用date命令获取结果

你可以使用POSIX标准的popen函数执行shell命令并读取输出,示例代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char time_str[32];
    FILE *cmd_fp = popen("date +'%H:%M:%S:%3N'", "r");
    if (cmd_fp == NULL) {
        perror("命令执行失败");
        return EXIT_FAILURE;
    }

    if (fgets(time_str, sizeof(time_str), cmd_fp) != NULL) {
        // 移除输出末尾自带的换行符
        time_str[strcspn(time_str, "\n")] = '\0';
        printf("时间结果:%s\n", time_str);
    }

    pclose(cmd_fp);
    return EXIT_SUCCESS;
}

说明:

  • 不需要在date命令外层套echo,直接调用date命令即可输出目标格式的时间,减少不必要的调用开销
  • 该方法依赖系统自带的date命令,仅适用于Linux/Unix类环境

方法2:原生C接口实现(无外部命令依赖)

如果不想调用外部shell命令,可以直接用clock_gettime系统调用获取时间后自行格式化,性能更高:

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

int main() {
    struct timespec ts;
    struct tm *local_tm;
    char buf[16];

    if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
        perror("获取时间失败");
        return EXIT_FAILURE;
    }

    local_tm = localtime(&ts.tv_sec);
    strftime(buf, sizeof(buf), "%H:%M:%S", local_tm);
    // 纳秒转毫秒,取前三位
    printf("%s:%03ld\n", buf, ts.tv_nsec / 1000000);
    return EXIT_SUCCESS;
}

说明:

  • 编译时如果提示找不到clock_gettime,可在编译指令末尾加-lrt参数链接实时库,比如gcc demo.c -o demo -lrt
  • 该方法不需要创建子进程执行外部命令,执行效率远高于方法1

内容的提问来源于stack exchange,提问作者user16438868

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:24:01