首页 > 代码库 > C实现改动可运行文件里的字符串,生成新的可运行文件
C实现改动可运行文件里的字符串,生成新的可运行文件
这样的技术经常使用在远程控制软件中。我们已有远程控制软件的server端。我们利用远程控制软件的client配置生成我们自己的服务端软件,实现server端的port及IP地址更新的功能。
下边看源码
#include <stdio.h>
#include <Windows.h>
int FindStr(char *destStr, char *srcStr, int destStrLen, int srcStrLen);
void ReplaceStr(char *destStr, char * srcStr, int beginPoint);
int main()
{
FILE *pReadFile;
FILE *pOutFile;
char *pFileBuf;
//打开我们要改动的源程序
if ((pReadFile = fopen("../custom/TestPE.exe", "rb")) == NULL)
{
printf("It‘s failure to open the readable file\n");
return -1;
}
//我们要生成的源程序
if ((pOutFile = fopen("../custom/TestPE1.exe", "wb")) == NULL)
{
printf("It‘s failure to open the writable file\n");
return -1;
}
fseek(pReadFile, 0L, SEEK_END);
int fileLen = ftell(pReadFile);
pFileBuf = (char *)malloc(fileLen + 1);
if (pFileBuf == NULL)
{
fclose(pReadFile);
return -1;
}
fseek(pReadFile,0L,SEEK_SET);
fread(pFileBuf, fileLen, sizeof(char), pReadFile);
pFileBuf[fileLen] = ‘\0‘;
//我们要改动成的字符串
char *modifyStr = "BBBBBBBBB";
//源程序中的字符串
char *findStr = "AAAAAAAAAAAAAAA";
int beginPoint;
//我们在读取的源程序数组中查找我们要查找的字符串的起始位置
beginPoint = FindStr(pFileBuf, findStr, fileLen, 0);
if (beginPoint == -1)
{
printf("It‘s failure to find the string\n");
return -1;
}
//替换我们的字符串
ReplaceStr(pFileBuf, modifyStr, beginPoint);
//生成我们改动后的源程序
fwrite(pFileBuf, fileLen, sizeof(char), pOutFile);
fclose(pReadFile);
fclose(pOutFile);
if (pFileBuf != NULL)
{
free(pFileBuf);
pFileBuf = NULL;
}
return 0;
}
int FindStr(char *destStr, char *srcStr, int destStrLen, int srcStrLen)
{
int i,j,findStrLen;
if (srcStrLen == 0)
{
findStrLen = strlen(srcStr);
}
else
{
findStrLen = srcStrLen;
}
for (i = 0; i < destStrLen; i++)
{
for (j = 0; j < findStrLen; j++)
{
if (destStr[i + j] != srcStr[j])
{
break;
}
}
if (j == findStrLen)
{
return i;
}
}
return -1;
}
void ReplaceStr(char *destStr, char *srcStr, int beginPoint)
{
int srcStrLen, i;
srcStrLen = strlen(srcStr);
for (i = 0; i < srcStrLen; i++)
{
destStr[beginPoint + i] = srcStr[i];
}
destStr[beginPoint + srcStrLen] = ‘\0‘;
}
C实现改动可运行文件里的字符串,生成新的可运行文件