您需要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 的参数留给读者作为练习。
免责声明:未经测试、非错误检查的代码仅用于演示目的。