简体   繁体   English

如何创建 function 像 printf 变量参数

[英]How to create function like printf variable argument

I was looking to implement an api like printf for my logging.我希望为我的日志记录实现一个 api,例如 printf。 It should be similar to calling printf.它应该类似于调用 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.我查看了变量参数的东西,但似乎我需要知道 arguments 的数量和类型。 so I need more help in that regard.所以我在这方面需要更多帮助。

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.这里的关键是vfprintf function,它将处理打印各种 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
}

This is an old question, but here is my simplified base solution that exactly mimics printf and should be expandable to other more specific uses, it's basically a generalized version of Michael Mior's answer:这是一个老问题,但这是我的简化基本解决方案,它完全模仿 printf 并且应该可以扩展到其他更具体的用途,它基本上是 Michael Mior 答案的通用版本:

#include <stdarg.h>

void print(const char* fmt, ...)
{
    va_list arg;
    va_start(arg, fmt);

    vprintf(fmt, arg); 
    //vprintf can be replaced with vsprintf (for sprintf behavior) 
    //or any other printf function preceded by a v

    va_end(arg);
}

(This seems to work in c++ as well, just without the library) (这似乎也适用于 c++,只是没有库)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM