【发布时间】:2018-06-29 08:54:14
【问题描述】:
我正在为学校做一个项目,我需要读取一个 .INI 文件来启动我的游戏变量。问题是,我似乎无法理解 strtok 的工作原理,此时我真的很困惑。
我知道我返回的是一个空结构,因为我不知道如何将特定值放入变量中!
这是我的 read_from_config.h
#ifndef READ_FROM_CONFIG_H
#define READ_FROM_CONFIG_H
#define MAXSTR 500
typedef struct {
unsigned int xdim;
unsigned int ydim;
unsigned int nzombies;
unsigned int nhumans;
unsigned int nzplayers;
unsigned int nhplayers;
unsigned int turns;
} CONFIG;
CONFIG read_config(char *argv[]);
#endif
这是我的 read_from_config.c
#include "read_from_config.h"
#include "example.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
CONFIG read_config(char *argv[]) {
char str[MAXSTR];
FILE *fp = NULL;
char *filename = argv[1];
char *token;
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Não foi possível abrir ficheiro de configuração.");
fprintf(stderr, "\nModo de uso: ./program_name config.ini");
}
while (fgets(str, MAXSTR, fp) != NULL) {
for (int i = 0; i != '\0'; i++) {
char *equal = strpbrk (str, "=");
if (equal) {
token = strtok(str, "=");
}
}
}
printf("%d", token[0]);
CONFIG config;
return config;
}
CONFIG.INI
; Dimension of the grid
xdim=20
ydim=20
; Inicial number of zombies and humans
nzombies=20
nhumans=20
; Number of zombies and humans controlled by players
nzplayers=0
nhplayers=1
; Number of maximum turns
maxturns=1000
【问题讨论】:
-
使用 .ini 文件是不是强迫症?而且,自己动手?
-
当心:你的 ini 文件让我知道分号 (
;) 也需要特殊处理......你应该想知道值键周围是否允许空格并且应该去掉。