简体   繁体   English

如何在fprintf中使用可变参数宏

[英]How to use Variadic macros with fprintf

I am trying to print logs into a file by writing macros. 我正在尝试通过编写宏将日志打印到文件中。 My macro looks like as shown below: 我的宏如下图所示:

#define LOG(fmt,...){\
    FILE *F;\
    F = fopen("output.txt","a");\
    fprintf(F,fmt " %s %d",__VA_ARGS__,__FILE__,__LINE__);}

And I plan to call LOG in the following format: 我计划以以下格式调用LOG:

LOG("values are : %d %d",num1,num2);

But when I compile I get the error 但是当我编译时我得到了错误

error: expected expression before ‘,’ token
     fprintf(F,fmt " %s %d",__VA_ARGS__,__FILE__,__LINE__);}

Can someone please explain where I am going wrong? 有人可以解释我要去哪里吗?

First of all you have to wrap you macro into a do-while loop, so it will be handled with expressions correctly. 首先,您必须将宏包装到do-while循环中,这样才能正确使用表达式进行处理。

#define LOG( fmt , ... ) do{  }while(0)

Then you have to make sure that fopen() call succeeds and that you close the file after usage. 然后,您必须确保fopen()调用成功,并且在使用后关闭文件。

FILE* f = fopen( "output.txt" , "a" ) ;
if( !f )
    break ;    //break works because you are in a loop
fclose( f ) ;    //also flushes the stream

Then you include the print in the full macro. 然后,将打印内容包含在完整的宏中。

#define LOG( fmt , ... )    \
        do{ \
            FILE* f = fopen( "output.txt" , "a" ) ; \
            if( !f )    \
                break ; \
            fprintf(f, fmt" %s %d\n",__VA_ARGS__,__FILE__,__LINE__);    \
            fclose( f ) ;   \
        }while( 0 )

The call is in the form: 调用的格式为:

LOG("values are : %d %d",4444,55555);

where you have to input at least one correct optional parameter, with the corresponding flag in the string. 在这里,您必须输入至少一个正确的可选参数,并在字符串中带有相应的标志。

#define LOG(fmt,...){\
    FILE *F;\
    F = fopen("output.txt","a");\
    fprintf(F,fmt " %d %d",__VA_ARGS__,__FILE__,__LINE__);}

Multiple issues 多个问题

  1. You never fclose F. 您从不fclose F。
  2. __FILE__ is a string. __FILE__是一个字符串。
  3. If you want to be able to call it without parameters __VA_ARGS__ must go at the end... 如果您想不带参数__VA_ARGS__调用它,必须在末尾...
  4. ... or use this little hack: ...或使用这个小技巧:

     #define LOG(fmt,...){\\ FILE *F;\\ F = fopen("output.txt","a");\\ fprintf(F,fmt " %s %d", ##__VA_ARGS__, __FILE__,__LINE__);} 

( ##__VA_ARGS__ is a GCC extension that removes the preceding comma if there are no args). ##__VA_ARGS__是GCC扩展名 ,如果没有参数则删除前面的逗号)。

Also check out this answer about "custom" printf-like functions. 还要检查有关“自定义”类printf函数的答案

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

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