parse_conf.c

来自「Linux下动态电源管理(Dynamic Power Management)的用」· C语言 代码 · 共 76 行

C
76
字号
#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <ctype.h>#include <string.h>#include "dpmd.h"static void strchrnull(char *str, int ch){	int i = 0;	while (str[i]) {		if (str[i] == ch) {			str[i] = '\0';			break;		}		i++;	}}int parse_config(const char *filename, struct dpmd_config *config){	FILE *fp;	char *line;	ssize_t n, len = 0;	char *name, *value;	fp = fopen(filename, "r");	if (fp == NULL) {		printf("Cannot open configuration file %s\n", filename);		exit(-1);	}	while ((n = getline(&line, &len, fp)) != -1) {		if (line[n - 1] == '\n')			line[n - 1] = '\0';		/* Because the file format does not know any form of quoting we		   can search forward for the next ';' character and if found		   make it terminating the line.  */		strchrnull (line, '#');		/* If the line is blank it is ignored.  */		if (line[0] == '\0')			continue;		name = strtok(line, "=");		value = strtok(NULL, "");		if (strcmp(name, "POLICY_HIGH") == 0) {			strncpy(config->policy_high, value, MAX_STR_LEN);		}		else if (strcmp(name, "POLICY_LOW") == 0) {			strncpy(config->policy_low, value, MAX_STR_LEN);		}		else if (strcmp(name, "POLL_INTERVAL") == 0) {			config->poll_interval = strtoul(value, NULL, 10);		}		else if (strcmp(name, "SUSPEND_INTERVAL") == 0) {			config->suspend_interval = strtoul(value, NULL, 10);		}		else if (strcmp(name, "CPU_INTERVAL") == 0) {			strncpy(config->cpu_interval, value, MAX_STR_LEN);		}		else if (strcmp(name, "PROGRAMS") == 0) {			strncpy(config->programs, value, MAX_STR_LEN);		}	}	if (line)		free (line);	fclose (fp);	return 0;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?