vsnprintf() Function

The vsnprintf() function in C stdio.h writes formatted data from a variable argument list to a sized buffer. It behaves much like printf(), but instead of sending the output to the standard output, it stores the result in a user-supplied buffer while ensuring that the output does not exceed a specified size. This is particularly useful for safely formatting strings to avoid buffer overflows.


Syntax of vsnprintf()

</>
Copy
int vsnprintf(char *s, size_t n, const char *format, va_list arg);

Parameters

ParameterDescription
sPointer to a buffer where the resulting C-string is stored. The buffer must be large enough to hold the formatted string.
nMaximum number of bytes to be written to the buffer, including the terminating null character. The resulting string will be at most n-1 characters long.
formatA C string that contains the format string, similar to that used in printf().
argA variable argument list initialized by va_start that provides the values to be formatted.

If the resulting formatted string would exceed n-1 characters, the extra characters are discarded, though the function still returns the total number of characters that would have been written. Also, the state of the variable argument list is altered by this call, so it must be properly managed using va_start and va_end.


Return Value

The function returns the number of characters that would have been written if the buffer were sufficiently large, not counting the terminating null character. If an encoding error occurs, a negative number is returned. Only when this return value is non-negative and less than n can the string be considered completely written into the buffer.


Examples for vsnprintf()

Example 1: Basic Usage of vsnprintf() for Formatting

This example demonstrates how to use vsnprintf() within a helper function to format a string containing an integer and a string.

Program

</>
Copy
#include <stdio.h>
#include <stdarg.h>

void formatMessage(char *buffer, size_t size, const char *format, ...) {
    va_list args;
    va_start(args, format);
    int ret = vsnprintf(buffer, size, format, args);
    va_end(args);
    printf("Formatted string: %s\n", buffer);
    printf("Return value: %d\n", ret);
}

int main() {
    char buffer[50];
    formatMessage(buffer, sizeof(buffer), "Number: %d, String: %s", 42, "example");
    return 0;
}

Explanation:

  1. A helper function formatMessage is defined to accept a buffer, its size, a format string, and variable arguments.
  2. The variable argument list is initialized with va_start and passed to vsnprintf() to format the string into the buffer.
  3. The formatted string and the return value (total characters that would have been written) are printed.
  4. The main function calls formatMessage with a sample format string and corresponding arguments.

Program Output:

Formatted string: Number: 42, String: example
Return value: 27

Example 2: Demonstrating Buffer Truncation with vsnprintf()

This example shows how vsnprintf() handles a situation where the formatted output exceeds the buffer capacity, resulting in a truncated string.

Program

</>
Copy
#include <stdio.h>
#include <stdarg.h>

void formatMessage(char *buffer, size_t size, const char *format, ...) {
    va_list args;
    va_start(args, format);
    int ret = vsnprintf(buffer, size, format, args);
    va_end(args);
    printf("Formatted string: %s\n", buffer);
    printf("Return value: %d\n", ret);
}

int main() {
    char buffer[20];
    formatMessage(buffer, sizeof(buffer), "This is a long string: %d %s", 12345, "test");
    return 0;
}

Explanation:

  1. The same helper function formatMessage is used with a smaller buffer size.
  2. The formatted string exceeds the available buffer space, so vsnprintf() writes only n-1 characters and truncates the rest.
  3. The function returns the total number of characters that would have been written if the buffer were large enough.
  4. The program prints the truncated string along with the complete length of the intended formatted output.

Program Output:

Formatted string: This is a long strin
Return value: 33

Example 3: Formatting a Log Message Using vsnprintf()

This example illustrates the use of vsnprintf() within a logging function to format a message that includes a floating-point value.

Program

</>
Copy
#include <stdio.h>
#include <stdarg.h>

void logMessage(const char *format, ...) {
    char buffer[100];
    va_list args;
    va_start(args, format);
    int ret = vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);
    printf("Log: %s\n", buffer);
    printf("Formatted length: %d\n", ret);
}

int main() {
    logMessage("Temperature is %.2f degrees Celsius.", 36.5);
    return 0;
}

Explanation:

  1. A logging function logMessage is defined to format and print log messages using a variable argument list.
  2. The function uses vsnprintf() to compose a formatted string into a buffer.
  3. The formatted log message and the length of the intended output are printed.
  4. The main function calls logMessage with a format string that includes a floating-point value.

Program Output:

Log: Temperature is 36.50 degrees Celsius.
Formatted length: 37