jit*_*hsk 1 c variadic-functions
我有一个函数log_info(从printf实现中复制)接受变量号.参数并将其传递给vprintf:
int log_info(const char *format, ...) {
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Run Code Online (Sandbox Code Playgroud)
我想在这些参数前面添加和附加字符串.因此,如果用户以这种方式调用上述函数:
log_info("at iteration %d, float value is %f", i, f);
Run Code Online (Sandbox Code Playgroud)
而不是打印
at iteration 4, float value is 102.34
Run Code Online (Sandbox Code Playgroud)
我想要打印
[INFO] [at iteration 4, float value is 102.34] [timestamp: xxxx]
Run Code Online (Sandbox Code Playgroud)
我可以分3个步骤完成
fprintf(stdout, "[INFO] [");
vprintf(stdout, format, arg);
fprintf(stdout, "] [timestamp:%f]", ts);
Run Code Online (Sandbox Code Playgroud)
但是程序是多线程的,因此我希望所有数据都可以在一次调用vprintf中编写(vprintf是线程安全的).
另一种选择是锁定一个互斥锁,然后按照上面所示的3个步骤编写它,但是如果将字符串附加到args并不是太复杂,我想尝试一下.
编辑:由于使用互斥锁而导致的性能开销并不是真正的问题,但除非必要,否则我不想使用它.
提前致谢
您想要将新字段添加到输出中,因此只需构造一个新的格式字符串.
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
int loginfo(const char *format, ...) {
int ret;
int len;
va_list ap;
char *new_fmt;
char *timestamp;
const char fmt_template[] = "[INFO] [%s] [timestamp: %s]";
/* Grab the timestamp now, since if we call it twice, it may change in length */
timestamp = get_time_string();
/* Calculate length for the augmented format string and allocate. */
len = snprintf(NULL, 0, fmt_template, format, timestamp);
new_fmt = malloc(len + 1);
/* Construct the new format string */
snprintf(new_fmt, len + 1, fmt_template, format, timestamp);
/* Print as before, using new format string */
va_start (ap, format);
ret = vfprintf (stdout, new_fmt, ap);
va_end (ap);
free(new_fmt);
return ret;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1109 次 |
| 最近记录: |