Function c returns a formatted string

I would like to do something like this:

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

so I'm looking for a function that returns a formatted string.

+7
source share
2 answers

Given that such a function does not exist, consider a slightly different approach: make writeLog printf-like, i.e. take a string and a variable number of arguments. Then format the message inside. This solves the memory management issue and does not violate the existing use of writeLog .

If you find this possible, you can use something on 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 } 
+5
source

There is no such function in the standard library, and it will never be in the standard library. If you want it, you can write it yourself. Here you need to think: who is going to allocate storage for the returned string, and who is going to free it? Will it be thread safe or not? Will there be a limit on the maximum length of the returned string or not?

+5
source

All Articles