1. linux开发---30.【C】实现内存替换
2. 代码如下
-
cong@msi:/work/cloud/test2$ cat test.cpp
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
#include <errno.h>
-
#include <zlib.h>
-
-
#define dbmsg(fmt, args ...) printf("%s:%s[%d]: "fmt"\n", __FILE__,__FUNCTION__, __LINE__,##args)
-
int memstr_my(unsigned char* src, int src_len, int start_pos)
-
{
-
int i;
-
unsigned char search[10] = {0,0,0,0,0,0,0,0,0,0};
-
int search_len = 10;
-
for(i=start_pos; i<src_len; i++)
-
{
-
if(0 == memcmp(&src[i], search, search_len))
-
break;
-
}
-
if(i==src_len)
-
return -1;
-
return i;
-
}
-
-
void mem_substitute(unsigned char *src, int src_len, unsigned char *dst, int dst_len)
-
{
-
unsigned char *pi, *po;
-
int search_len, left_len;
-
int pos;
-
pi = src;
-
po = dst;
-
search_len = 10;
-
pos = memstr_my(pi, src_len, 0);
-
left_len = src_len;
-
if(pos > 0)
-
{
-
while(pos > 0 )
-
{
-
memcpy(po, pi, pos);
-
pi += pos + search_len;
-
po += pos;
-
left_len -= pos;
-
left_len -= search_len;
-
pos = memstr_my(pi, left_len, pos);
-
}
-
memcpy(po, pi, left_len);
-
}
-
else
-
{
-
//if not found, just copy
-
memcpy(po, pi, src_len);
-
}
-
}
-
-
int main(int ac, char *av[])
-
{
-
int i;
-
unsigned char src[128];
-
unsigned char dst[128];
-
for(i=0; i<128; i++)
-
src[i] = i%128;
-
-
for(i=0; i<10; i++)
-
src[i+12] = 0;
-
-
for(i=0; i<10; i++)
-
src[i+48] = 0;
-
-
mem_substitute(src, 128, dst, 128);
-
for(i=0; i<128; i++)
-
{
-
printf("%d=0x%x ", i, dst[i]);
-
if((i+1)%10 == 0)
-
printf("\n");
-
}
-
printf("\n");
-
return 0;
-
}
-
cong@msi:/work/cloud/test2$
3. 代码下载
mem_substitute.rar(下载后改名为mem_substitute.rar)
阅读(1127) | 评论(0) | 转发(0) |