stpcpy returns the pointer to the terminating \0 character of the target string. This immediately makes clear the purpose of stpcpy and the rationale behind its existence: this function is intended to be used as an intelligent replacement to strcat function in situations when you need to concatenate multiple sub-strings into one string.
strcat works pretty poorly in such application. The problem with strcat is that it rescans the destination string every time you add something to it, thus doing lots of unnecessary work and basically generating more heat than light. For example, the following code suffers from that problem
const char *part1, *part2, *part3, *part4;
...
char buffer[size]; /* assume that `size` is calculated properly */
strcpy(buffer, part1);
strcat(buffer, part2);
strcat(buffer, part3);
strcat(buffer, part4);
stpcpy(stpcpy(stpcpy(stpcpy(buffer, part1), part2), part3), part4);
And if you don't like chained calls, you can use an intermediate pointer to store the return value of intermediate stpcpy calls
char *end = buffer;
end = stpcpy(end, part1);
end = stpcpy(end, part2);
end = stpcpy(end, part3);
end = stpcpy(end, part4);
Of course it is worth mentioning that strcpy and strcat are standard functions, while stpcpy is not. Refrerence : SOF
No comments:
Post a Comment