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



>我目前正在用DHT11温度和湿度传感器和LCD显示屏对我的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 %dn", current_time, temp, humidity);
    fclose (logfd);
    /* Write to current file */
    FILE *currfd;
    currfd = fopen(CURRENTFILE, "w");
    fprintf (currfd, "%ld %d %dn", 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(日/月/年小时:分钟:秒)格式有什么建议吗?

根据@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 %dn", dt, temp, humidity);

请参阅localtime()strftime()的POSIX描述。

最新更新