修改一个类ini文件中某几个变量的值的C代码
2008-12-23 15:51
435 查看
同事的一个朋友让她写一个小程序,修改一个文本文件中某几个变量的值(这个文本文件和ini文件比较像,但并不完全符合ini文件的格式,因此不能调用WritePrivateProfileString来修改)。听到这我马上就想说,用Perl或Python来做这事,该是多么简单啊!不过既然现在工作是用VC,就写一段温习温习吧。
#include <stdio.h> #include <stdlib.h> #include <string.h> char *readfile(const char *filename) { FILE *file = fopen(filename, "rb"); char *buf = NULL; if (file) { fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); buf = (char*)malloc(size + 1); fread(buf, 1, size, file); fclose(file); buf[size] = 0; } return buf; } int writefile(const char *filename, const char *buf) { FILE *file = fopen(filename, "wb"); int done = 0; if (file) { done = fwrite(buf, 1, strlen(buf), file); fclose(file); } return done; } char *getline(char *buf, char *line) { static char *last_buf = NULL; char *p = NULL; if (last_buf != buf) { p = strtok(buf, "/n"); last_buf = buf; } else { p = strtok(NULL, "/n"); } if (p) { strcpy(line, p); } return p; } int main(int argc, char* argv[]) { char *buf = readfile("test.txt"); const SECT_COUNT = 2; char *repl_sect[SECT_COUNT*2] = {"server.max-worker", "5", "server.max-connections", "200000"}; if (buf) { char *outbuf = (char*)malloc(strlen(buf)*2); *outbuf = 0; char *line = (char*)malloc(strlen(buf)); while (getline(buf, line)) { for (int i=0; i<SECT_COUNT; i++) { char *p_sect = repl_sect[i*2]; if (strncmp(line, p_sect, strlen(p_sect)) == 0) { strcpy(line + strlen(p_sect), " = "); strcat(line, repl_sect[i*2+1]); strcat(line, "/r"); break; } } strcat(line, "/n"); strcat(outbuf, line); } writefile("test.txt", outbuf); free(line); free(outbuf); free(buf); } return 0; }
相关文章推荐
- 修改一个类ini文件中某几个变量的值的C代码
- 习惯把运行的class的名字作为文件名保存 如果文件中类是public修饰,那么类名必须和文件名相同 一个java文件中可以放几个public的类??? java变量:变量是用来标识一块内存的,变量必
- 【代码提取】提取一个文件夹里面的所有Java文件的类名函数名和变量名
- 读取ini配置文件时,成员变量的内存数据被隐式修改了
- 用GDB修改可执行文件的代码和变量(gdb)
- laravel,视图文件将变量代码注释,会出现的一个怪现象
- java读取和修改ini配置文件实例代码
- 基本上,把switch,用设计模式代替,肯定是bug和过度设计。想想,本来修改一个文件几行代码可以解决的问题,变成修改3-6个类才能实现一样的功能。不是傻是什么?
- delphi制作资源文件(二)一个A.exe释放出B.exe 并且修改b.exe变量的值
- 批量修改一个文件夹下所有的文件后缀
- 双系统boot.ini文件代码
- Linux chmod命令修改文件与文件夹权限命令代码
- PHP.ini修改配置下载上传文件大小
- HDFS的API调用,创建Maven工程,创建一个非Maven工程,HDFS客户端操作数据代码示例,文件方式操作和流式操作
- 【原创】实现Word模板文件中的BookMark允许多次填写修改(含代码)
- zf-关于评价器的开关所在的配置文件,与代码如何修改。
- git修改服务器上前一个提交未merge的代码片段
- Eclipse 分屏显示同一个代码文件
- 系统多种资源文件代码示例(例如一个系统同时具有中文简体,中文繁体,英文,日文等不同资源文件)(示例代码下载)
- 关于服务代码的几个文件存储路径