我正在尝试修改a.out文件。我正在寻找一个字符串“abc”,然后用“xyz”替换它。然后我必须写入a.out 我正在使用fwrite来实现这一目标。但它似乎给了seg错误。 我可以写一个新的文件与所做的更改。但我无法写信给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;
}
答案 0 :(得分:1)
在打开文件的fpw句柄
之前,没有关闭文件的fp句柄