修改配置文件,当时是用作ftp的动态修改接口函数的修改

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_PATH  "/home/vsftpd.conf"
#define NTP_PATH "/home/ntp.conf"
#define NTP_CMD "ntpdate" //ntp服务器参数修改基准


void setConfigFile(char* configName,char* configBuffer)
{
	int i = 0;
	char lineBuff[256];// 存储读取一行的数据
	memset(lineBuff,0,256);

	FILE* fp  = fopen(DEFAULT_PATH,"r");
	if(fp == NULL)
		perror("open file\n");

	fseek(fp,0,SEEK_END);
	int configLen = ftell(fp); //配置文件长度
	fseek(fp,0,SEEK_SET);
	int configBufferLen = strlen(configBuffer);
	char sumBuf[configBufferLen + configLen];
	memset(sumBuf,0,sizeof(configBufferLen + configLen)); //原文件长度 + 修改字符长度
	while(fgets(lineBuff,256,fp) != NULL)
	{
		if(strlen(lineBuff) < 4) // 空行
		{
			strcat(sumBuf,lineBuff);
			continue;
		}
		char* linePos = NULL;
		linePos = strstr(lineBuff,"="); // 没有匹配行
		if(linePos == NULL)
		{
			strcat(sumBuf,lineBuff);
			continue;
		}
		int lineNum = linePos - lineBuff;
		char lineName[lineNum + 1];
		memset(lineName,0,sizeof(lineName));
		strncpy(lineName,lineBuff,lineNum);
		if(lineName[0] == '#')
		{
			for(i = 0; i < lineNum;i++)
			lineName[i] = lineName[i+1];
		}
		//"=" 前匹配
		if(strcmp(configName,lineName) == 0)
		{
			strcat(sumBuf,configName);
			strcat(sumBuf,"=");
			strcat(sumBuf,configBuffer);
			strcat(sumBuf,"\n");
		}
		else
		{
			strcat(sumBuf,lineBuff);
		}
	}
	fclose(fp);
	remove(DEFAULT_PATH);
	FILE* f = fopen(DEFAULT_PATH,"w+");
	fputs(sumBuf,f);
	fclose(f);
}

/*
**ntp服务器对时设置IP,IP的设置和一个shell命令有关,所以以shell命令为参考标准
*/
void setNtpServerIP(char* ip)
{
	FILE* fp = fopen(NTP_PATH,"r");
	if(fp == NULL)
		perror("open file!\n");
	char lineBuf[128];
	memset(lineBuf,0,128);
	fseek(fp,0,SEEK_END);
	int len = ftell(fp);
	fseek(fp,0,SEEK_SET);
	char sumBuf[strlen(ip) + len];
	memset(sumBuf,0,sizeof(strlen(ip)) + len);
	while(fgets(lineBuf,128,fp) != NULL)
	{
		int lenIP = 0;
		char* linePos = NULL;
		linePos = strstr(lineBuf,NTP_CMD);
		if(linePos == NULL)
			continue;
		else
		{
			int lineNum = linePos - lineBuf;
			int lineCp = lineNum + strlen(NTP_CMD) + 1;
			while(lineBuf[lineCp] != '\n')
			{
				lineBuf[lineCp++] = ip[lenIP++];
				if(lenIP > strlen(ip))
					break;
			}
			strncpy(sumBuf,lineBuf,strlen(ip) + len);
		}

	}
	fclose(fp);
	remove(NTP_PATH);
	FILE* f = fopen(NTP_PATH,"w+");
	fputs(sumBuf,f);
	fclose(f);
}

int main()
{
	setNtpServerIP("192.168.0.111"); //参数为待修改IP
	setConfigFile("local_root","/home/dir"); //参数为配置项 + 配置值
	setConfigFile("write_enable","YES");
	setConfigFile("anon_mkdir_write_enable","NO");
	setConfigFile("anon_upload_enable","NO");
	setConfigFile("chown_username","whoever");
}


Logo

更多推荐