C(Unix)中基于文件的配置处理 [英] File based configuration handling in C (Unix)

查看:52
本文介绍了C(Unix)中基于文件的配置处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是编程时最常见的任务/问题之一;您需要将应用程序的配置存储在某处.

This is probably one of the most common tasks / problems when programming; You need to store the configuration of your application somewhere.

在尝试创建Web服务器或其他应用程序时,由于我对编程的主要兴趣是体系结构,因此我希望代码保持尽可能的简洁.这导致我想要将配置存储在一个文件中,而无需重新编译该软件即可进行更改.

While I'm trying to create a webserver or other applications, I'd like to keep the code as clean as possible since my main interest in programming is architecture. This results in me wanting to store configurations in a file which can be changed without having to re-compile the software.

我不是在这里重新发明轮子或类似的东西,所以我想做的是在* nix上用C创建一个配置读取器.该配置看起来很像其他任何软件的配置. Apache,vsftpd,MySQL等.

I'm not here to re-invent the wheel or anything like that, so what I'd like to do is creating a Configuration reader in C on *nix. The configuration might look a lot like any other software's configuration; Apache, vsftpd, MySQL, etc.

基本问题是:如何从文本文件读取并有效地处理每一行(以纯C语言编写)?我需要使用fgetc()并处理每个字符吗?

The basic question is: How do you read from a textfile and process each line efficiently (in pure C)? Do I need to use fgetc() and process each char?

推荐答案

好的,让我们谈谈其他部分.您需要考虑您想拥有的语言".在UNIX世界中,规范版本的类型可能是由空格分隔的文本(请考虑/etc/hosts)或由:"分隔的文本(如/etc/passwd).

Okay, so let's hit the other part. You need to think about what you'd like to have as your "language". In the UNIX world, the sort of canonical version is probably whitespace-delimited text (think /etc/hosts) or ":" delimited text (like /etc/passwd).

您有几个选择,从某种意义上讲,最简单的方法是使用scanf(3).同样,请阅读手册页以获取详细信息,但是如果行条目类似于

You have a couple of options, the simplest in some sense being to use scanf(3). Again, read the man page for details, but if a line entry is something like

port    100

那么您将寻找

char inbuf[MAXLINE];
int  val;

scanf("%s %d\n", &inbuf[0], &val);

如果编写简单的FSA解析,则可以得到更大的灵活性:一次从行中读取一个字符,并使用有限的自动机来定义操作.

You can get a bit more flexibility if you write a simple FSA parse: read characters one at a time from the line, and use a finite automaton to define what to do.

这篇关于C(Unix)中基于文件的配置处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆