未知长度的格式化的数据写入到一个字符串(C编程) [英] writing formatted data of unknown length to a string (C programming)

查看:98
本文介绍了未知长度的格式化的数据写入到一个字符串(C编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的C函数:

int sprintf ( char * str, const char * format, ... );

格式化的数据写入到一个字符串。作为str中传递数组的大小应足以包含整个格式的字符串。但是,如果格式化字符串的长度不知道提前?它具有的长度是未知如何能该功能(或类似的其另一个功能)一起使用的写入格式化数据?

writes formatted data to a string. The size of the array passed as str should be enough to contain the entire formatted string. However, what if the length of the formatted string is not known ahead of time? How can this function (or another function like it) be used write formatted data which has a length which is unknown?

例如:

#include <stdio.h>

int main ()
{
  char buffer [13];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a %d char long string\n",buffer,n);
  return 0;
}

的缓冲器必须是13或更大,以便为这个工作。如果字符串长度是未知的,以及缓冲液,例如已设置为5,这是行不通的。我需要的东西,可以动态分配或重新分配的缓冲区中发生为比缓冲更大串。

The buffer needs to be 13 or greater in order for this to work. If the string length was unknown, and the buffer, for example has been set for 5, this would not work. I need something that can dynamically allocate or reallocate the buffer for strings that happen to be bigger than the buffer.

推荐答案

你想要的是这两个功能之一:
* 的snprintf http://libslack.org /manpages/snprintf.3.html )。这需要输出缓冲器作为它的第二个参数的长度,并且如果缓冲器是用于存放结果太小它将返回所需的字符数,允许你重新分配一个较大的缓冲区。
* asprintf 。它需要一个的char ** 参数,并分配足够的内存来保存输出,只要那么多的连续虚拟内存可用。你必须调用免费如果你用它做在程序退出之前,可能需要记忆的东西。从内​​存中删除

What you want is one of these two functions: * snprintf (http://libslack.org/manpages/snprintf.3.html). It takes the length of the output buffer as its second argument, and if the buffer is too small for the result it will return the number of characters needed, allowing you to reallocate a larger buffer. * asprintf. It takes a char ** argument and allocates enough memory to hold the output, as long as that much contiguous virtual memory is available. You have to call free to remove it from memory if you're done with it before the program exits and may need the memory for something else.

这篇关于未知长度的格式化的数据写入到一个字符串(C编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆