2013-05-14 58 views
-1
gcc (GCC) 4.7.2 
c89 

你好,獲得兩個不同的時間

我公司開發的示例程序應該得到的開始時間和結束時間之間的差之間的時間差。然後我用秒來計算這兩次之間已經過了多少天。

這是針對用戶指定天數後的日誌記錄應用程序。日誌將被翻轉並設置新的開始時間。用戶可以決定日誌將被替換多少天。

我增加了一個小小的睡眠來獲得一般想法,但通常這會記錄幾天。

這是最好的和最便攜的(Linux/Windows)的方式來做到這一點?這個設計有什麼潛在的缺陷?

非常感謝您的任何建議,

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

int main(void) 
{ 
    time_t start_timestamp; 
    time_t end_timestamp; 
    struct tm time_days; 
    double seconds = 0; 
    size_t cumulative_days = 0; 
#define FORMAT_TIME_SIZE 64 
    char format_time[FORMAT_TIME_SIZE]; 

#define DAY 3600  /* Seconds in one day */ 
#define MAX_DAYS 10 /* Roll over log after 10 days */ 

    /* Current time of starting application */ 
    time(&start_timestamp); 
    time_days = *localtime(&start_timestamp); 

    /* Print the current time at the start */ 
    memset(format_time, 0, sizeof format_time); 
    strftime(format_time, sizeof format_time, "%c", &time_days); 
    printf("timestamp start [ %s ]\n", format_time); 

    /* Simulate a simple sleep. This could be logging for many days */ 
    sleep(10); 

    /* Current time after delay print the results */ 
    time(&end_timestamp); 
    time_days = *localtime(&end_timestamp); 
    memset(format_time, 0, sizeof format_time); 
    strftime(format_time, sizeof format_time, "%c", &time_days); 
    printf("timestamp end [ %s ]\n", format_time); 

    /* Get the current difference in seconds */ 
    seconds = difftime(end_timestamp, start_timestamp); 
    printf("Seconds elapsed [ %f ]\n", seconds); 

    /* Calculate how many days have elapsed */ 
    cumulative_days = DAY * seconds; 

    /* What are we going to do */ 
    if(cumulative_days <= MAX_DAYS) { 
     printf("Delete log and start over\n"); 
    } 
    else { 
     printf("Not there yet, keep appending the current log\n"); 
    } 

    return 0; 
} 
+1

應該在[Code Review](http://codereview.stackexchange.com/)上,我想。 – Kninnug 2013-05-14 10:18:35

回答

1

的替代,可以說是更簡單的方法是使用當前日期作爲日誌文件名mylog.22的擴展,這樣你得到一個自動翻轉,並保持記錄的最後一個月。

相關問題