gpt4 book ai didi

c - 替换二进制文件中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:40 24 4
gpt4 key购买 nike

我正在尝试编写一个 *nix 程序来复制自身并替换二进制文件中的字符串。复制过程似乎不起作用。

代码如下:

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>

#define BUFSIZE 10
#define FILENAME "token"

void findstring(const char *exe, const char* str)
{
char buf[BUFSIZE];
int line_num = 1;
int i = 0, find_result = 0;
FILE *fp = fopen(exe, "rb");
if(fp == NULL)
exit(-1);

FILE *out = fopen("out", "wb");
if(out == NULL)
exit(-1);

while(fgets(buf, BUFSIZE, fp) != NULL) {
if((strstr(buf, str)))
{
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", buf);
find_result++;

// reverse "token" string in the output
for(i = 0; i< BUFSIZE; i++)
{
if(strstr(&buf[i], "t") != NULL)
buf[i] = 'n';
else if(strstr(&buf[i], "o") != NULL)
buf[i] = 'e';
else if(strstr(&buf[i], "k") != NULL)
buf[i] = 'k';
else if(strstr(&buf[i], "e") != NULL)
buf[i] = 'o';
else if(strstr(&buf[i], "n") != NULL)
buf[i] = 't';
}
}
line_num++;

fputs(buf, out);
}

if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}

fclose(fp);
fclose(out);
}

int main(int argc, char **argv, char **envp)
{
// argv[1] = FILENAME;

char buf[1024];
int fd, rc;

findstring(argv[0], "token");

if(argc == 1) {
printf("\n\n%s [file to read]\n\n", argv[0]);
exit(1);
}

printf("FILENAME macro = %s", FILENAME);

if(strstr(argv[1], "token") != NULL) {
printf("\n\nYou may not access '%s'\n\n", argv[1]);
exit(2);
}

fd = open(argv[1], O_RDONLY);
if(fd == -1) {
printf("\n\nUnable to open %s\n\n", argv[1]);
exit(3);
}

rc = read(fd, buf, sizeof(buf));

if(rc == -1) {
printf("\n\nUnable to read fd %d\n\n", fd);
exit(4);
}

write(1, buf, rc);

return 0;
}

“Token”字符串应该在输出二进制文件(“nekot”)中反转,findstring 函数负责执行此任务。还值得注意的是,找到的匹配项数量严格取决于 BUFSIZE 常量。

此代码缺少什么?谢谢

最佳答案

考虑一下这是做什么的:

  if(strstr(&buf[i], "t") != NULL)
buf[i] = 'n';

这将从索引 i 开始搜索缓冲区,如果字符串 "t" 出现在缓冲区中的任何位置,它将用 替换第一个字符n.所以如果你的缓冲区有

a string with token inside.

for 循环的第一次迭代会将其更改为

n string with token inside.

随着循环的进行,你会得到

nnnnnnnnnnith token inside.

经过 10 次迭代,最终

nnnnnnnnnnnnnnnekooooooooo.

其他问题:

  • fgets 读取一个字符串,直到一个换行符或最多 BUFSIZE-1 个字符。很可能有等同于换行符的字节。
  • 无论您读取了多少字节,您都在扫描 BUFSIZE 个字节。
  • fputs 将写入第一个 NUL 字节。如果您的输入二进制文件中的任何位置都有 NUL 字节,则缓冲区中 NUL 之后的内容将丢失。

上面的意思是你可能想使用fread/fwrite而不是fgets/fputs,你想要仔细检查快照读取或写入的返回值。

关于c - 替换二进制文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com