更改文件中的内容
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; }
相关文章推荐
- 文件中关键字后面是什么及长度
- 利用URL Protocol实现网页调用本地应用程序
- 初亏博弈门道
- 华为OJ(统计每个月兔子的总数)
- UVA 10158 War 并查集
- Python并发编程
- maven使用Nexus私有仓库进行管理
- js方法格式化数字,加入千分符,并可以指定小数点位数
- IOS 多线程(4) --线程通讯
- HDU 2222 AC自动机
- 【POJ1456】【并查集变形】【技巧】
- 《数据库系统概念第六版》读书笔记
- C++常用术语及其英文翻译的含义和简单用途总结(八)
- accordion 全部折叠
- ARC(Automatic Reference Counting)
- 得到文件某行的偏移量(get byte offset of a line)
- mybatis 动态sql
- sql 查询所有数据库、表名、表字段总结
- 基于JQuery实现滚动到页面底端时自动加载更多信息
- vector删,erase和remove难怪--【STL】