Chinaunix首页 | 论坛 | 博客
  • 博客访问: 180647
  • 博文数量: 63
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 69
  • 用 户 组: 普通用户
  • 注册时间: 2013-03-18 13:11
文章分类
文章存档

2013年(64)

我的朋友

分类: LINUX

2013-04-17 09:55:52

公司笔试和面试中常要你编写strcpy/strcmp/memcpy/memcmp/strstr/atoi 等等这样的基础函数的实现。
我想在这儿总结下:(如下代码都是来自最新Linux kernel的库函数)
---------------------------------------------------------------------------------------
  1. //strcpy in linux kernel linux-3.3/linux/lib/string.c
  2. char *strcpy(char *dest, const char *src) {
  3.          char *tmp = dest; //很多时候可以在这儿对传入参数进行有效检查。内核里面没有这样做。
  4.          while ((*dest++ = *src++) != '\0')
  5.              /* nothing */;
  6.     return tmp;
  7.  }
-----------------------------------------------------------------------------------------
  1. int strcmp(const char *cs, const char *ct)
  2.  {
  3.          unsigned char c1, c2;
  4.  
  5.          while (1) {
  6.                  c1 = *cs++;
  7.                  c2 = *ct++;
  8.                  if (c1 != c2)
  9.                          return c1 < c2 ? -1 : 1;
  10.                  if (!c1)
  11.                          break;
  12.          }
  13.          return 0;
  14.  }
------------------------------------------------------------------------------------------------
  1. void *memcpy(void *dest, const void *src, size_t count)
  2.  {
  3.          char *tmp = dest;
  4.          const char *s = src;
  5.  
  6.          while (count--)
  7.                  *tmp++ = *s++;
  8.          return dest;
  9.  }
-----------------------------------------------------------------------------------------------
  1. int memcmp(const void *cs, const void *ct, size_t count) {
  2.           const unsigned char *su1, *su2;
  3.           int res = 0;
  4.        
  5.           for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
  6.                  if ((res = *su1 - *su2) != 0)
  7.                      break;
  8.           return res;
  9. }
-----------------------------------------------------------------------------------------------
  1. char *strstr(const char *s1, const char *s2)
  2.  {
  3.          size_t l1, l2;
  4.  
  5.          l2 = strlen(s2);
  6.          if (!l2)
  7.                  return (char *)s1;
  8.          l1 = strlen(s1);
  9.          while (l1 >= l2) {
  10.                  l1--;
  11.                  if (!memcmp(s1, s2, l2))
  12.                          return (char *)s1;
  13.                  s1++;
  14.          }
  15.          return NULL;
  16.  }
-----------------------------------------------------------------------------------------------

阅读(1085) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~