| Yep, that's intended use case for strncpy(). It's not really suitable for general purpose programming like the OP is doing. It won't null terminate the string if the buffer is filled, which will cause you all sorts of problems. If the buffer is not filled, it will write extra null bytes to fill the buffer (not a problem, but unnecessary). On freebsd you have strlcpy(), Windows has strcpy_s() which will do what the OP needs. I remember someone trying to import strlcpy() into Linux, but Ulrich Drepper had a fit and said no. You just never assume a string is null terminated when reading, using strnlen or strncpy when reading as well. Not really possible when dealing with operating system level APIs that expect and require null-terminated strings. It's safer and less error-prone to keep everything null terminated at all times. Or just write in C++ and use std::string, or literally any other language. C is terrible when it comes to text strings. |
strlcpy() came from OpenBSD and was later ported to FreeBSD, Solaris, etc.