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

int main()
{
    char prompt[] = "Give me a line:";
    char str[6];
    char line[100];

    printf("%s\n", prompt);
    fgets(line, sizeof(line), stdin);
    printf("Original line read by fgets(): [%s]\n", line);

#ifdef CASE1 /* Using snprintf() */

    int n = snprintf(str, sizeof(str), "%s", line);
    printf("Truncated using snprintf(): [%s]\n", str);

    // snprintf() returns the number of chars it would have printed
    // (not including the null terminator) if there were no truncation
    //
    // Normally this return value isn't very useful, but if you don't use 
    // the return value, the compiler will warn about possible trancation.
    // Use -Wno-format-truncation compiler flag to disable this warning.
    //
    printf("Length of string if it hadn't been truncated: %d\n", n);

#endif
#ifdef CASE2 /* Using strncpy() INCORRECTLY */

    strncpy(str, line, sizeof(str));
    printf("Truncated using strncpy(): [%s]\n", str);

#endif
#ifdef CASE3 /* Using strncpy() correcly */

    strncpy(str, line, sizeof(str) - 1);
    str[sizeof(str) - 1] = '\0';
    printf("Truncated using strncpy(): [%s]\n", str);

#endif
}
