【发布时间】:2016-02-02 02:19:12
【问题描述】:
我正在尝试修改 a.out 文件。我正在寻找一个字符串“abc”,然后用“xyz”替换它。然后我必须把它写进 a.out 我正在使用 fwrite 来完成此操作。但它似乎给出了段错误。 我能够用所做的更改写入一个新文件。但我无法写信给 a.out。
在 Linux 上运行。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
static char a[100] = "abc";
char ch, fileName[20] = "a.out";
FILE *fp, *fpw;
long size;
int i;
fp = fopen(fileName,"rb");
if (fp == NULL)
printf ("FILE OPEN FAILED.\n");
else
{
fseek(fp,0,SEEK_END);
size = ftell(fp);
printf("%d\n",size);
//buffer = (char *) malloc(size+1);
unsigned char buffer[size+1];
fseek(fp,0,SEEK_SET);
fread(buffer,size,1,fp);
int pos_search = 0;
int pos_text = 0;
int len_search = 3;
int len_text = size;
for (pos_text = 0; pos_text < len_text - len_search;++pos_text)
{
if(buffer[pos_text] == a[pos_search])
{
++pos_search;
if(pos_search == len_search)
{
// match
printf("match from %d to %d\n",pos_text-len_search,pos_text);
break;
}
}
else
{
pos_text -=pos_search;
pos_search = 0;
}
}
printf("%c\n",buffer[1]);
i = pos_text-len_search+1;
buffer[i] = 'x';
buffer[i+1] = 'y';
buffer[i+2] = 'z';
fpw = fopen("a.out","rb+");
fwrite(buffer,1,size-1,fpw);
fclose(fpw);
}
return 0;
}
【问题讨论】:
-
如果你不缩进你的代码,它会让你的生活变得困难数百万倍。
-
@MillieSmith:更不用说可能试图提供帮助的人们的生活了。感谢您清理 OP 的代码。
-
我可以通过上面的代码在我的 Linux 机器上将“abc”更改为“xyz”。您最好发布错误消息以进行调试。
-
@rici 不客气。 @OP:您检查 fopen 是否为读取操作返回有效的 FILE 指针,但您不为写入操作执行此操作。我打赌
fopen("a.out","rb+");失败并返回null,因为“a.out”是该程序的可执行文件并且当前正在运行。 -
另外,请参阅这个问题:stackoverflow.com/questions/1893235/…
标签: c