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

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

问题描述

这可能是在编程时最常见的任务/问题之一;你需要存储应用程序的配置的某个地方。

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

虽然我尝试创建一个网络服务器和/或其他应用程序,我想保持code尽可能的干净,因为我在编程的主要兴趣是结构。这导致我想在一个文件中存储的配置,可以无需重新编译软件被改变。

While im trying to create a webserver and / 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配置读卡器等什么。配置看起来很像任何其他软件配置;阿帕奇,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 softwares configurations; Apache, vsftpd, mysql, etc.

的基本问题是:如何从一个文本和处理每行有效地读取(纯C)?我是否需要使用龟etc(),并处理每一个字符?

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

,那么您会寻找类似

then you'll be looking for something like

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天全站免登陆