您的位置:首页 > 编程语言

修改一个类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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐