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

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

问题描述

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

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

当我尝试创建网络服务器或其他应用程序时,我希望代码尽可能干净,因为我对编程的主要兴趣是架构.这导致我想将配置存储在一个文件中,该文件无需重新编译软件即可更改.

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

那么你会寻找类似的东西

then you'll be looking for something like

char inbuf[MAXLINE];
int  val;

scanf("%s %d
", &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天全站免登陆