我正在尝试编写一个* 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;
}
应该在输出二进制文件(“ 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.
其他事宜:
BUFSIZE-1
字符为止。可能存在与换行符等效的字节。BUFSIZE
无论您读取多少字节,都在扫描字节。上面的意思是您可能要使用fread
/fwrite
而不是fgets
/ fputs
,并且要仔细检查快照读取或写入的返回值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句