Posted By

zava on 08/11/10


Tagged

textmate strncpy


Versions (?)

strncpy.c


 / Published in: C
 

  1. /*
  2.  * Copy src to dst, truncating or null-padding to always copy n bytes.
  3.  * Return dst.
  4.  * This routine completes in a single loop but runs slower than libc
  5.  * because 'write_nul' is evaluated for every char.
  6.  * Ansi string only!
  7.  */
  8. char* _strncpy(char* dst, const char* src, int n)
  9. {
  10. char* d = dst;
  11. const char* s = src;
  12. int write_nul = 0;
  13. while (n-- > 0)
  14. {
  15. *d++ = write_nul ? 0 : *s;
  16. if (!write_nul) { write_nul = (*s == 0); }
  17. s++;
  18. }
  19. return dst;
  20. }
  21.  
  22. int main()
  23. {
  24. char dst[10];
  25. printf("%sn", _strncpy(dst, "01234567", 5));
  26. printf("%sn", _strncpy(dst, "0123", 5));
  27. printf("%sn", _strncpy(dst, "0123456789ABC", 12));
  28. }

Report this snippet  

You need to login to post a comment.