更改文件中的内容

/*
    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;


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值