if I want to construct a const char *
out of several primitive type arguments, is there a way to build the string using a similar to the printf
?
views:
114answers:
2
+2
A:
You can use sprintf, which is exactly like printf except the first parameter is a buffer where the string will be placed.
Example:
char buffer[256];
sprintf(buffer, "Hello, %s!\n", "Beta");
beta
2010-04-28 04:52:46
i think you mean sprintf, fprintf prints to files
yjerem
2010-04-28 04:54:34
Also, use `snprintf` rather than `sprintf`.
dreamlax
2010-04-28 04:56:43
ah yes. as far as I recall, fprintf takes a `fd` not an actual pointer.
piggles
2010-04-28 04:58:27
whoops... sorry.
beta
2010-04-28 05:05:43
@Mechko: `fprintf` takes a `FILE*`, not a file descriptor, although you can obtain a `FILE*` from a file descriptor easily enough by calling `fdopen`.
dreamlax
2010-04-28 09:45:23
+8
A:
You're probably looking for snprintf.
int snprintf(char *str, size_t size, const char *format, ...);
A simple example:
char buffer[100];
int value = 42;
int nchars = snprintf(buffer, 100, "The answer is %d", value);
printf("%s\n", buffer);
/* outputs: The answer is 42 */
Just to add, you don't actually need to use snprintf
- you can use the plain old sprintf
(without the size argument) but then it is more difficult to ensure only n characters are written to the buffer. GNU also has a nice function, asprintf
which will allocate the buffer for you.
Nick Presta
2010-04-28 04:55:44
+1 Neat, that page for `asprintf` led to the [Obstack](http://www.gnu.org/software/libtool//manual/libc/Obstacks.html) documentation, which looks pretty useful in some situations.
Greg Hewgill
2010-04-28 05:19:41