简体   繁体   English

c函数返回格式化字符串

[英]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. 所以我正在寻找一个返回格式化字符串的函数。

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? 是否会对返回的字符串的最大长度进行限制?

Given no such function exists, consider a slightly different approach: make writeLog printf-like, ie take a string and a variable number of arguments. 如果不存在这样的函数,请考虑稍微不同的方法:使writeLog print,即获取字符串和可变数量的参数。 Then, have it format the message internally. 然后,让它在内部格式化消息。 This will solve the memory management issue, and won't break existing uses of writeLog . 这将解决内存管理问题,并且不会破坏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
}

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

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