【问题标题】:What does fprintf() do in the following macro?fprintf() 在下面的宏中做了什么?
【发布时间】:2013-12-31 15:02:32
【问题描述】:

此宏用于错误记录。 LOG_MESSAGE 宏打印文件名后跟行号,最后打印信息/错误消息。参数prio决定消息的优先级(即是信息消息还是错误),stream可能是STD_OUT

#include <stdio.h>

#define INFO    1
#define ERR 2
#define STD_OUT stdout
#define STD_ERR stderr
#define LOG_MESSAGE(prio, stream, msg, ...)
do {\
    char *str;\
    if (prio == INFO)\
        str = "INFO";\
    else if (prio == ERR)\
        str = "ERR";\
    fprintf(stream, "[%s] : %s : %d : "msg" \n", \
    str, __FILE__, __LINE__, ##__VA_ARGS__);\
} while (0)

int main(void)
{
    char *s = "Hello";

        /* display normal message */
    LOG_MESSAGE(ERR, STD_ERR, "Failed to open file");

    /* provide string as argument */
    LOG_MESSAGE(INFO, STD_OUT, "%s Geeks for Geeks", s);

    /* provide integer as arguments */
    LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 10, 20, (10 + 20));

    return 0;
}

【问题讨论】:

  • 说真的。你觉得实时渲染预览是干什么用的?!
  • 您对printf 语句的##__VA_ARGS__ 部分有疑问吗?
  • 我在问 fprintf 部分是如何工作的
  • 这不会编译,它缺少一个斜杠。
  • @user3130036 请在下面查看我的回答。您还可以从任何 C 参考文献中了解有关 fprintf 的更多信息:cplusplus.com/reference/cstdio/fprintf。我希望这会有所帮助!

标签: c macros


【解决方案1】:

fprintf() 在下面的宏中做了什么?

fprintf 是一个将格式化数据写入的函数。在上面的示例中,流只是将stream 传递给LOG_MESSAGE。如果查看传入宏的参数,您会发现它需要prio -> 优先级、stream -> 要写入的流、msg -> 要写入的实际消息,以及一些附加变量论据。

main 中,您在写入STD_ERRSTD_OUT 流之间进行选择。

顺便说一句:

宏只是在编译前由预处理器执行的复制粘贴操作。

【讨论】:

    猜你喜欢
    • 2014-01-22
    • 2013-01-14
    • 1970-01-01
    • 2016-02-14
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多