views:

94

answers:

5
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);

I don't want to output anything via fprintf,but only the result of "Error in pcap_findalldevs: %s\n", errbuf,what's the function for that?

+4  A: 

snprintf allows you to format to a char buffer and performs bounds checking to ensure the buffer is not overrun.

The commonly used sprintf does not perform bounds checking, and as such is inherently unsafe.

James McNellis
But I need to allocate enough space for `char * string` before calling it,how do I know how much space is required?
httpinterpret
@httpinterpret: With your example, the space required is `strlen("Error in pcap_findalldevs: \n") + strlen(errbuf) + 1` (it's not always so easy to calculate, though).
caf
+1  A: 

That is sprintf() which also has some useful variations, like vsprintf() which takes a pointer to an argument list. There are also buffer protection versions in some implementations.

wallyk
+1  A: 

sprintf copies the result to a char * instead of writing it to stdout or a file.

Syntax differences

printf(const char format, ...)

fprintf(FILE * file, const char format, ...)

sprintf(char * string, const char format, ...)

Delan Azabani
+3  A: 
int sprintf(char * ptr, const char * format, ...)

Writes the output and a terminating null to a buffer at ptr, returns the number of characters written excluding the null. Dangerous if you don't know how big your output should be, it will blindly write past the end of the buffer.

int snprintf(char * ptr, size_t n, const char * format, ...)

Same as sprintf, but will write a maximum of n characters, including the trailing null. Returns the number of characters that would be written if n was large enough, so that you can reallocate your buffer if necessary.

int asprintf(char ** ptr, const char * format, ...)

Same as sprintf except a double pointer is passed in, the buffer will be resized if necessary to fit the output. This is a GNU extension, also available in BSD, it can be emulated like (Ignoring error checking)

int asprintf(char ** ptr, const char * format, ...){
    va_list vlist;
    va_start(vlist,format);
    int n = vsnprintf(NULL,0,format,vlist);
    *ptr = realloc(*ptr,n+1);
    n = vsnprintf(*ptr,n+1,format,vlist);
    va_end(vlist);
    return n;
}
Scott Wales
I don't want to restrict the length of the result string,how do I make it work for arbitary long string?
httpinterpret
The `asprintf` function will resize the buffer to the required length itself, otherwise use `snprintf` to check the necessary buffer size.
Scott Wales
A: 

sprintf is the original call, but should be considered deprecated in favor of snprintf which allows you to pass a size. Another alternative is asprintf, which will allocate a string large enough to hold the result.

drawnonward