Programming Tips - C/C++: strlcpy Copy a strings ensuring no buffer overflows and a terminating NUL

Date: 2007oct16 Language: C/C++ Keywords: LPCSTR, LPSTR, LPTSTR, LPCTSTR Q. C/C++: strlcpy Copy a strings ensuring no buffer overflows and a terminating NUL A. If you don't have one builtin, use this.
size_t strlcpy(LPTSTR dst, LPCTSTR src, const size_t bufsize) { size_t len; if (src == NULL) return 0; len = lstrlen(src); if (dst == NULL) return len; if (len >= bufsize) len = bufsize - 1; memcpy(dst, src, len * sizeof(TCHAR)); dst[len] = '\0'; return len; }