Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c function to return formatted string

Tags:

c

string

printf

I would like to do something like this:

writeLog(printf("This is the error: %s", error));

so i am looking for a function which returns a formatted string.

like image 473
Zulakis Avatar asked Jun 24 '12 19:06

Zulakis


2 Answers

Given no such function exists, consider a slightly different approach: make writeLog printf-like, i.e. take a string and a variable number of arguments. Then, have it format the message internally. This will solve the memory management issue, and won't break existing uses of writeLog.

If you find this possible, you can use something along these lines:

void writeLog(const char* format, ...)
{
    char       msg[100];
    va_list    args;

    va_start(args, format);
    vsnprintf(msg, sizeof(msg), format, args); // do check return value
    va_end(args);

    // write msg to the log
}
like image 194
eran Avatar answered Sep 23 '22 20:09

eran


There is no such function in the standard library and there will never be one in the standard library.

If you want one, you can write it yourself. Here's what you need to think about:

  1. Who is going to allocate the storage for the returned string?
  2. Who is going to free the storage for the returned string?
  3. Is it going to be thread-safe or not?
  4. Is there going to be a limit on the maximum length of the returned string or not?
like image 20
bmargulies Avatar answered Sep 23 '22 20:09

bmargulies