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?
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?
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.
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, ...)
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;
}
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.