更正 C 代码日志文件上的时间戳

Correcting timestamp on C code log file

我目前正在使用 DHT11 温度和湿度传感器和液晶显示屏对我的 Raspberry Pi(型号 B)进行编程。我编写了一个 C 脚本,它将从温度传感器获得的值记录到状态文件中,然后将其添加到日志文件中。脚本如下:

#include <time.h>

#define LOGFILE "/var/log/temp.log"
#define CURRENTFILE "/var/temp.data"



/* Saves the date time and humidity to a log file and current file */


void write_value (int temp, int humidity) {

    time_t current_time;
    current_time = time(NULL);

    /* Write to log file */
    FILE *logfd;
    logfd = fopen (LOGFILE, "a");
    fprintf (logfd, "%ld %d %d\n", current_time, temp, humidity);
    fclose (logfd);

    /* Write to current file */
    FILE *currfd;
    currfd = fopen(CURRENTFILE, "w");
    fprintf (currfd, "%ld %d %d\n", current_time, temp, humidity);
    fclose (currfd); 

}

但是,它有效;我在日志文件中得到的输出如下:

1428539174 16 41
1428539232 17 40
1428539257 18 40
1428539304 19 39
1428539319 19 39

第一行是日期和时间戳、温度和湿度。

关于我如何确定日期和时间以及将其更改为 DD/MM/YYYY HH:MM:SS (Day/Month/Year Hour:Min:Sec),您有什么建议吗格式?

根据@pmg 的建议,脚本更改为:

#include <time.h>

#define LOGFILE "/var/log/temp.log"
#define CURRENTFILE "/var/temp.data"



/* Saves the date time and humidity to a log file and current file */


void write_value (int temp, int humidity) {

    char dt[20]; // space enough for YYYY-MM-DD HH:MM:SS and terminator
    struct tm tm;
    time_t current_time;
    current_time = time(NULL);
    tm = *localtime(&current_time); // convert time_t to struct tm
    strftime(dt, sizeof dt, "%Y-%m-%d %H:%M:%S", &tm); // format

    /* Write to log file */
    FILE *logfd;
    logfd = fopen (LOGFILE, "a");
    fprintf (logfd, "%s %d %d/n", dt, temp, humidity);
    fclose (logfd);

    /* Write to current file */
    FILE *currfd;
    currfd = fopen(CURRENTFILE, "w");
    fprintf (currfd, "%s %d %d/n", dt, temp, humidity);
    fclose (currfd); 

}

time_t 值转换为 struct tm,然后适当地格式化

char dt[20]; // space enough for DD/MM/YYYY HH:MM:SS and terminator
struct tm tm;
time_t current_time;

current_time = time(NULL);
tm = *localtime(&current_time); // convert time_t to struct tm
strftime(dt, sizeof dt, "%d/%m/%Y %H:%M:%S", &tm); // format

fprintf(currfd, "%s %d %d\n", dt, temp, humidity);

查看 localtime() and strftime() 的 POSIX 描述。