Creating C formatted strings (not printing them)

前端 未结 7 1053
广开言路
广开言路 2020-12-04 12:07

I have a function that accepts a string, that is:

void log_out(char *);

In calling it, I need to create a formatted string on the fly like:

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 12:22

    http://www.gnu.org/software/hello/manual/libc/Variable-Arguments-Output.html gives the following example to print to stderr. You can modify it to use your log function instead:

     #include 
     #include 
    
     void
     eprintf (const char *template, ...)
     {
       va_list ap;
       extern char *program_invocation_short_name;
    
       fprintf (stderr, "%s: ", program_invocation_short_name);
       va_start (ap, template);
       vfprintf (stderr, template, ap);
       va_end (ap);
     }
    

    Instead of vfprintf you will need to use vsprintf where you need to provide an adequate buffer to print into.

提交回复
热议问题