/strlcpy.c

https://github.com/arthurbryant/c-test · C · 36 lines · 32 code · 2 blank · 2 comment · 12 complexity · 3f0b370dee063699303e2e78ccded28b MD5 · raw file

  1. #include <stdio.h>
  2. #include <string.h>
  3. int strlcpy(char *dst, const char *src, size_t n)
  4. {
  5. if(dst == NULL || src == NULL)
  6. return -1;
  7. char *d = dst;
  8. const char *s = src;
  9. if(n > 0)
  10. {
  11. while(--n != 0)
  12. {
  13. if((*d++ = *s++) == '\0')
  14. break;
  15. }
  16. }
  17. if(n == 0)
  18. {
  19. *d = '\0';
  20. while(*s++);
  21. }
  22. return s-src-1;
  23. }
  24. int main(int argc, char * argv[])
  25. {
  26. char a[5];
  27. int len = sizeof(a)/sizeof(char);
  28. //strlcpy(a, "abcdef", len);
  29. //strcpy(a, "hello, world");
  30. int count;
  31. count = strlcpy(a, "hello, world", 5);
  32. printf("%s %d\n", a, count);
  33. return 0;
  34. }