您的位置:首页 > 其它

更改文件中的内容

2015-08-25 13:13 267 查看
/*
program使命:查找文件中字符串,并用其他字符串代替
思想: 找到字符串,然后将文件指针移动到要替换的字符串的首部,然后写入要使用的字符串,然后在文件buffer中把后面的片段写到文件中。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

long sizeByFile(const char *filename,char *mode)
{
long size=0;
FILE *fp = NULL;
fp = fopen(filename,mode);
if(NULL == fp)
{
printf("file open error\n");
exit(0);
}
fseek(fp,0,SEEK_END);
size = ftell(fp);
rewind(fp);
fclose(fp);
return size;
}
int main(int argc,char *argv[])
{
char final[128]={0,};
FILE *fp=NULL;
getcwd(final,sizeof(final));
char *str ="/libpcap/remote-ext.h>";
strncat(final,str,strlen(str));
int final_size=0;
final_size = strlen(final);
long f_size = sizeByFile("pcap.h","r");
char *f_buf = (char*)malloc(sizeof(char)*f_size);
if(f_buf == NULL)
{
printf("pcap buf malloc error!\n");
return -1;
}
fp = fopen("pcap.h","r+");
if(fp == NULL)
{
printf("pcap.h open error!\n");
return -1;
}
int read_counts = fread(f_buf,1,f_size,fp);
if(read_counts != f_size)
{
printf("pcap.h read error!\n");
return -1;
}
int   len = 0;

char *pos_prev  = strstr(f_buf,"remote-ext.h");
if(pos_prev == NULL)
{
printf("search error!\n");
return -1;
}

char *slash = strstr(pos_prev,"\n");
printf("pos_prev:%s\n",slash+1);
long ev = slash+1-pos_prev;
//    long len =
long offset = pos_prev - f_buf;
printf("offset:%d\n",offset);

fseek(fp, offset , SEEK_SET);
fwrite(final,1,final_size,fp);
fwrite("\n",1,1,fp);
fwrite(slash,1,read_counts-offset-ev,fp);
fclose(fp);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息