You basically invent strlcpy , which was introduced in 1996 - see strlcpy and strlcat - a sequential, secure, string copy and concatenation of an article by Todd Miller and Theo de Raadt. You may not have heard about this because you refused to be added to glibc , called "terribly ineffective BSD shit" supporting glibc, and fought that day even when it is accepted by all other operating systems - see Damien's Secure Portableability document Miller (Part 4: Choosing the Right API).
You can use strlcpy on Linux using the libbsd project (packaged in Debian, Ubuntu and other distributions) or simply copying the source code, the code is easy to find on the Internet (for example, using two links in this answer).
But back to your question about what would be most effective in your case when you are not using the length of the source string, here is my idea based on the strlcpy source from OpenBSD at http://cvsweb.openbsd.org/cgi-bin /cvsweb/src/lib/libc/string/strlcpy.c?rev=1.11 , but without checking the length of the source line, which can be very long, but with the correct ending '\ 0':
char *d = str; // the destination in your example const char *s = string; // the source in your example size_t n = max; // the max length in your example /* Copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { if ((*d++ = *s++) == '\0') break; } } /* Not enough room in dst, add NUL */ if (n == 0) { if (max != 0) *d = '\0'; /* NUL-terminate dst */ }
Here is the version of strlcpy at http://cantrip.org/strlcpy.c that uses memcpy:
#include <stdlib.h> /* for size_t */ size_t strlcpy(char *dst, const char *src, size_t size) { const size_t len = strlen(src); if (size != 0) { memcpy(dst, src, (len > size - 1) ? size - 1 : len); dst[size - 1] = 0; } return len; }
Which one will be more efficient, I think, depends on the source string. For very long source lines, strlen can take a lot of time, and if you don't need to know the original length, perhaps the first example will be faster for you.
It all depends on your data, so profiling real data will be the only way to find out.