2016-11-08 38 views
0

因此,作爲一個任務的一部分,我們一直在考慮這個骨架功能來完成:關於C中給定的格式轉換time_t表示爲一個字符串

char *time2str(time_t time) { 
    static char *str_fmt = "%02d/%02d/%4d %02d:%02d"; 
    char *time_s = ""; // appropriate string allocation here 

    return time_s; 
} 

但是我很新的C和掙扎讓我的頭左右我在做什麼錯誤(也指針是如何工作的)......我一直在嘗試使用localtime得到struct與我可以訪問我需要添加到字符串中給出的具體值格式。事情是這樣的:

char *time2str(time_t time) { 
    static char *str_fmt = "%02d/%02d/%4d %02d:%02d"; 

    struct tm *info; 
    info = localtime(&time); 

    char *time_s = (str_fmt, info->tm_mday, info->tm_mon...etc...); 

    return time_s; 
} 

不過我剛開始在編譯警告和錯誤無論怎樣我嘗試做(除去str_fmt,只是把在報價格式在time_s開始,使用info.tm_mday等,而不是info->tm_mday)。然而,似乎沒有任何影響,我無法在網上找到任何有助於我按照我們的要求解決問題的任何內容。

誰能幫助?可能值得一提的是,我們正在使用MINIX系統調用在MINIX 3.2.1上執行此操作。

+0

有趣的代碼上塊正是它是如何給我們的「骨架」的實現,我是假設它是正確的 – transiti0nary

+0

我認爲你的老師希望你'malloc',然後分配使用'sprintf'。 –

+0

如果只有POSIX有['asprintf()'](http://man7.org/linux/man-pages/man3/asprintf.3.html)。唉,它不是POSIX。 (雖然,它是在Linux的/ GNU/MacOS的/最BSD版本可用。)我不知道有多少緩衝區溢出將是可以避免的,如果我們使用它,而不是'的malloc()'+'的snprintf()'(或更糟的是,'的sprintf()')。 –

回答

2

使用你給我們什麼,我採用的功能應該是:

char *time2str(time_t time) { 
    static char *str_fmt = "%02d/%02d/%4d %02d:%02d"; 

    // Convert to struct tm 
    // localtime returns a pointer, so shallow copy to info 
    struct tm info = *localtime(&time); 

    // Allocate memory for ##/##/#### ##:## 
    char *time_s = malloc(17); // Space for 16 chars and eos 
    if (NULL == time_s) {// Handle error.....} 
    sprintf(time_s, str_fmt, info.tm_mon + 1, info.tm_mday, 1900 + info.tm_year, 
      info.tm_hour, info.tm_min); 

    return time_s; 
} 
+0

謝謝,我剛剛使用上面的註釋實現了同樣的事情,我不再收到編譯錯誤。認爲這有助於我更好地掌握一些C的概念(來自Java):) – transiti0nary

0

管理字符串是在C代碼一項棘手的任務有多年的成功經驗時,意想不到的情況存在可能會失敗。

考慮格式"%02d/%02d/%4d %02d:%02d"。這通常會期望一個大小爲16 + 1的數組(對於空字符)。這是同一類型的編碼,對於Y2K bugs做出這一個9999年後需要更多空間考慮,允許time_t代表時間到遙遠的未來,並試圖形成基於其最大值的日期/時間字符串的系統 - - >緩衝區溢出。

相反,允許在struct tm所有潛在值,並提供慷慨的臨時緩衝區。然後分配。

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

// Max length needed for a `int` as decimal text 
#define INT_STR_LEN (sizeof(int)*CHAR_BIT/3 + 2) 

#define TIME2STR_FMT "%02d/%02d/%04d %02d:%02d" 
// Worst case size - and them some 
#define TIME2STR_SZ (sizeof TIME2STR_FMT + 5*INT_STR_LEN) 

char *time2str(time_t time) { 

    struct tm *info = localtime(&time); 
    if (info == NULL) return NULL; 

    char buf[TIME2STR_SZ]; 
    int n = snprintf(buf, sizeof buf, TIME2STR_FMT, info->tm_mon + 1, info->tm_mday, 
     info->tm_year + 1900, info->tm_hour, info->tm_min); 
    if (n < 0 || n >= sizeof buf) return NULL; 

    // Allocate and copy 
    size_t sz = strlen(buf) + 1; 
    char *time_s = malloc(sz); 
    if (time_s) { 
    memcpy(time_s, buf, sz); 
    } 

    return time_s; 
} 

int main(void) { 
    time_t t; 
    puts(time2str(time(&t))); 
    return 0; 
} 
相關問題