封装 printf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[root@localhost ~]# cat print.c
#include "stdio.h"
#include <stdarg.h>

void WriteLog(const char *format, ...)
{
char buff[2048];
const int size = sizeof(buff);

va_list args;
va_start(args, format);
vsnprintf(buff, size, format, args);
va_end(args);

printf(buff);
}


int main()
{
printf( "linux:[%f][%s][%d][%zd][%4d]\n", 1/3.0, "hello", 1992, 0x00FFFFFFFFFF, 42);
WriteLog("linux:[%f][%s][%d][%zd][%4d]\n", 1/3.0, "hello", 1992, 0x00FFFFFFFFFF, 42);

return 0;
}

编译运行

1
2
3
4
5
[root@localhost ~]# gcc -Wall print.c && ./a.out
linux:[0.333333][hello][1992][1099511627775][ 42]
linux:[0.333333][hello][1992][1099511627775][ 42]
[root@localhost ~]#
[root@localhost ~]#

截断显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@localhost ~]# cat print.c
#include "stdio.h"
int main()
{
// 5字符, 左对齐, 只显示2字符
printf("%-*.*s\n", 5,2,"123");
return 0;
}



[chunli@localhost ~]$ gcc /tmp/main.c -o /tmp/main.c.o
[chunli@localhost ~]$ /tmp/main.c.o
12
[chunli@localhost ~]$