您需要sprintf
,它與printf
類似,但將結果「打印」到緩衝區而不是屏幕上。
返回指針到一個靜態緩衝液:
char *time2str(time_t time) {
static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";
static char time_s[20]; // ugly, 20 is hopefully enough
//^static is important here, because we return a pointer to time_s
// and without static, the time_s buffer will no longer exist once the
// time2str function is finished
sprintf(time_s, str_fmt, time.....);
return time_s;
}
或(更好),我們提供了一個緩衝器(足夠長),其中轉換後的字符串是要被放置:
void time2str(time_t time, char *time_s) {
static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";
sprintf(time_s, str_fmt, time.....);
return time_s;
}
...
char mytime[20]; // ugly, 20 is hopefully enough
time2str(time, mytime);
printf("mytime: %s\n, mytime);
或time2str函數返回一個新分配的緩衝區,該緩衝區將包含轉換後的字符串。該緩衝區必須稍後用free
釋放。
char *time2str(time_t time) {
static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";
char *time_s = malloc(20); // ugly, 20 is hopefully enough
sprintf(time_s, str_fmt, time.....);
return time_s;
}
...
char *mytime = time2str(time);
printf("mytime: %s\n, mytime);
free(mytime);
完成sprintf
的參數僅供讀者參考。
聲明:未經測試的非錯誤檢查代碼僅用於演示目的。
一般來說,始終使用至少'snprintf'。它很容易通過普通的'sprintf'創建緩衝區溢出! – hyde