How to strcpy and return the number of copied characters?

I want to copy a string with a terminating zero to another location and want to know how long the copied string has been. Efficiency is paramount. There is a function strcpythat can achieve this, but does not return how many copies are actually copied.

Of course, I could find out by simply calling strlenafter that to determine the length of the copied string, but that would mean repeating the characters in the string again a second time, although I strcpyhave to keep track of how many letters copy anyway. For performance reasons, I don't want such a second workaround.

I know that writing your own strcpywith a simple copy of char -by-char is easy, but I thought the standard library could apply magic that does strcpyfaster than a naive char -by-char.

So what is the best method for strcpyand get the number of characters copied without re-moving the line?

+4
source share
5 answers

Many systems support stpcpythat returns a pointer to the end of the destination. You can subtract the original destination pointer, and this way you get the length.

+6
source

If you really need it, 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; 
}

.

+3

C , , , . , :

size_t StrCpyLen(char *dest, const char *src) {
    const char *s = src;
    while ((*dest++ = *s++))
        ;
    return s - src - 1;
}

-

K & R : src , src .

+2

sprintf :

size_t len_strcpy(char *dest, char const *src) { 
    return sprintf("%s", dest, src);
}

, , strcpy, strlen. , Microsoft sprintf .., ( Intel) . strcpy/strlen .

+2

- strlen(), memcpy(), , , , , , .

memcpy() Ben

gcc 5.1.0 -O1:

  • part1: 62181 -
  • part2: 195093 - strcpy/strlen
  • part3: 45568 - strlen/memcpy

-O2 part1 part3 , part2 :

  • part1: 62234
  • part2: 12129
  • part3: 45565

-O2, strlen() .

+1

Source: https://habr.com/ru/post/1621151/


All Articles