A safe string copy function to handle char*
05 Mar 2011
strcpy is not safe as it cannot limit the number of characters to be copied. strcpy_s is safe, but it cannot deal with char*. After searching for a while, I think I need a safe string copy function to handle char* and here it is:
// Initial dstRemainChar should be sizeof(dst)-1. And manually pending '\0' is needed.
size_t str_copy(char* dst, size_t& dstRemainChar, char* src) {
char c = *src;
size_t copied = 0;
while (c != '\0') {
if (!dstRemainChar) {
break;
}
*dst = c;
dst++;
src++;
dstRemainChar--;
copied++;
c = *src;
}
return copied;
}
An example of use:
char dst[80];
strcpy_s<80>(dst, "First ");
// Here strcpy_s<74>(dst + 6, "Second"); cannot compile!
size_t dstRemainChar = 80 - 1 - 6;
char *pdst = dst + 6;
pdst += str_copy(pdst, dstRemainChar, "Second ");
pdst += str_copy(pdst, dstRemainChar, "Third");
pdst[0] = 0;
cout << "Line: " << dst << endl;cout << "Remained Character: " << dstRemainChar << endl;