previous | start | next

fgets, strncpy, snprintf

Each of these alternate versions of i/o functions has an extra parameter for the size of the array.

The function will not write more than this limit into the array.

Using these functions (correctly) prevents overflowing the character arrays.

        const int N = 5;
        char b[N];

        /**
        * 1. Not enough room in b for "Hello, World!"
        *    but only 4 characters will be copied and a null 
        *    byte added.
        */

        strncpy(b, "Hello, World!", N-1);
        b[N-1] = '\0';
        

        /**
        * 2. fgets reads at most the specified number of bytes minus 1
        *    from the input line and stores it in b and adds a null
        *    byte, but stops reading after a newline is read. The
        *    newline is stored if it is read. The third parameter
        *    is of type FILE *, pointer to FILE. stdin, stdout, and
        *    stderr are of this type. The fopen function is used to
        *    open a named file; it returns a FILE * for the opened file.
        */

        fgets(b, N, stdin);

        /**
        * 3. Converts time in ticks since Januarty 1, 1970 (or the
        *    'epoch' starting date) to a string representation of
        *    the current date and time and stores it in b. E.g.,
        *    "Thu May 14 09:29:24 2009" copied to b, but copies 
        *    at most the specified number of characters - 1 and 
        *    then adds a null byte. So only "Thu " will be copied
        *    if N is 5.
        */
        time_t ticks = time(0);  // current time in ticks since epoch
        snprintf(b, N, "%.24s", ctime(&ticks));

     


previous | start | next