您需要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