I want to copy a null-terminated string to another location and want to know how long the copied string was. Efficiency is of utmost importance. There ist the strcpy function which can achieve this, but it does not return how many characters are actually copied.
Of course, I could find this out by simply calling strlen afterwards to detect the length of the copied string, but this would mean traversing the characters in the string again a second time, although strcpy has to track how many characters it copies anyway. For performance reasons, I do not want such a second traversal.
I know that writing an own strcpy with a simple char-by-char copy is easy, but I thought that the standard library might apply magic which makes strcpy faster than a naive char-by-char implementation.
So, what is the best method to strcpy and receive the number of copied characters without traversing the string again?
Returned Value The strcpy() function returns the value of string1.
Description. The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.
The strncpy() function returns a pointer to string1 .
Problem with strcpy(): The strcpy() function does not specify the size of the destination array, so buffer overrun is often a risk. Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk.
Many systems support stpcpy which returns pointer to the end of the destination. You can subtract original destination pointer and this way you'll get the length.
I would use sprintf to do the job:
size_t len_strcpy(char *dest, char const *src) {
return sprintf("%s", dest, src);
}
It's hard to guess whether this will really be slower or faster than using strcpy followed by strlen though. With the Microsoft compiler, for one example, they recently did some work on the implementation of sprintf and such, so (on Intel) it uses vector instructions and runs really fast. With older versions of the compiler, there would be a lot better chance of the strcpy/strlen winning.
If you really need this it would be very easy to write your own:
unsigned int lenstrcpy(char dest[], const char source[]) {
unsigned int i = 0;
while ((dest[i] = source[i]) != '\0') {
i++;
}
return i;
}
Here is a live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With