httpinterpret
httpinterpret

Reputation: 6709

Is there a function akin to fprintf but only returns the result of formated string in C?

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?

Upvotes: 1

Views: 155

Answers (5)

drawnonward
drawnonward

Reputation: 53669

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.

Upvotes: 0

Scott Wales
Scott Wales

Reputation: 11696

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;
}

Upvotes: 3

James McNellis
James McNellis

Reputation: 355079

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.

Upvotes: 4

Delan Azabani
Delan Azabani

Reputation: 81394

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, ...)

Upvotes: 1

wallyk
wallyk

Reputation: 57774

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.

Upvotes: 1

Related Questions