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

时间:2015-04-09 13:20:20

标签: c logging time timestamp raspberry-pi

我正在使用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

第一行是日期&amp;时间戳,温度和湿度。

您对我如何确定日期和安排有任何建议吗?时间,以及将其更改为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); 

}

1 个答案:

答案 0 :(得分:3)

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()strftime()的POSIX说明。