Reading and writing formatted strings

suggest change

Use snprintf to format data into an array. Unlike sprintf, it accepts the destination capacity and therefore does not write past the end of the array:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char buffer[50];
    const double pi = 3.1415926;

    int length = snprintf(buffer, sizeof buffer, "pi = %.7f", pi);
    if (length < 0 || (size_t)length >= sizeof buffer) {
        fputs("Formatting failed or was truncated\n", stderr);
        return EXIT_FAILURE;
    }

    puts(buffer);
    return EXIT_SUCCESS;
}

snprintf returns the number of characters that would have been written, excluding the terminating null character. A nonnegative result greater than or equal to the destination capacity indicates truncation.

Use sscanf to parse a string only when its conversion rules fit the input. Limit every %s conversion to one less than the destination capacity and check how many fields were converted:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char sentence[] = "date: 06-06-2012";
    char label[16];
    int day;
    int month;
    int year;

    if (sscanf(sentence, "%15[^:]: %2d-%2d-%4d",
               label, &day, &month, &year) != 4) {
        fputs("Could not parse date\n", stderr);
        return EXIT_FAILURE;
    }

    printf("%s -> %04d-%02d-%02d\n", label, year, month, day);
    return EXIT_SUCCESS;
}

Field widths prevent buffer overflow but do not validate calendar ranges. Validate the parsed values before using them as a date.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents