我正在尝试修改 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;
}
最佳答案
在打开文件的 fpw 句柄之前,您没有关闭文件的 fp 句柄
关于c - 尝试修改a.out。使用 fwrite 写入 a.out 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143955/