Zulakis
Zulakis

Reputation: 8384

c function to return formatted string

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.

Upvotes: 10

Views: 10366

Answers (2)

bmargulies
bmargulies

Reputation: 100040

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?

Upvotes: 6

Eran
Eran

Reputation: 22020

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
}

Upvotes: 8

Related Questions