如何创建如printf可变参数函数 [英] How to create function like printf variable argument

查看:174
本文介绍了如何创建如printf可变参数函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找实现如printf一个API,用于我的记录。它应类似于调用printf的。
例如:

I was looking to implement an api like printf for my logging. It should be similar to calling printf. For example:

persistent_log(LogType0, "This is buffered writing %d", i);

我看着可变参数的东西,但似乎我需要知道电话号码和放大器;类型的参数那里。所以我需要在这方面更多的帮助。

I looked into variable argument stuff , but it seems I need to know the number & type of arguments there. so I need more help in that regard.

推荐答案

下面是从过去的项目中,我发现很适合我的工作的摘录。一些初始化步骤,当然缺少。这里的关键是 vfprintf 功能,将处理打印各种争论的细节。

Here's an excerpt from a past project that I found to work well for me. Some initialization steps are of course missing. The key here is the vfprintf function which will handle the details of printing the various arguments.

void _proxy_log(log_level_t level, const char *fmt, ...)
    __attribute__((format (printf, 2, 3)));

#define proxy_log(level, fmt, ...) _proxy_log(level, fmt"\n", ##__VA_ARGS__)

void _proxy_log(log_level_t level, const char *fmt, ...) {
    va_list arg;
    FILE *log_file = (level == LOG_ERROR) ? err_log : info_log;

    /* Check if the message should be logged */
    if (level > log_level)
        return;

    /* Write the error message */
    va_start(arg, fmt);
    vfprintf(log_file, fmt, arg);
    va_end(arg);

#ifdef DEBUG
    fflush(log_file);
    fsync(fileno(log_file));
#endif
}

这篇关于如何创建如printf可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆