strncpy and fgets are the more secure substitutes to strcpy and gets, respectively. The less secure versions are prone to buffer overflows, especially the notorious gets. Both functions fill a pre-allocated memory for strings while reading at most a specified number of characters. However, the ways these functions treat the source and destination are slightly different.
strncpy
char* strncpy (char *destination, const char *source, size_t num);
strncpy reads up to num characters, not including the null character. Therefore, if you have a string with strlen of num, strncpy will copy the whole string to destination but not the null character, which you will have to set manually. If strlen(source) is less than num, then the null character will be set. Therefore, for a strncpy with num, you will want the destination to have at least num+1 characters allocated.
fgets
char* fgets( char *str, int num, FILE *stream);
fgets reads up to num-1 characters and then sets the null character for every destination string (perhaps except when num < 1). Therefore, for a fgets with num, you will want the destination to have at least num characters allocated, unlike strncpy. fgets will stop when it encounters a newline, EOF, or num-1 characters. If it is reaches a newline, fgets will also copy the newline to the destination string. Note that you can set the stream parameter to stdin if needed.






