我有一个科学仪器的守护进程,它需要保留大约 100 个唯一变量。目前,这些设置以二进制形式存储在显式地址中,并且每个设置都使用唯一的 getter 和 setter 进行访问。这是完全无法维护的。我想将设置组合在合理的结构中,并将这些结构保存到文件中。如果文件不完整,我也会有默认值。什么库或技术可以让我用尽可能少的代码行来保存和恢复这些结构?
3 回答
"Shortest" have several meanings
- fast to process
- eating as little as memory as possible
- easy and quick to code
I would suggest to use a simple textual format to serialize them, probably JSON (or maybe YAML or XML). The advantage of such formats is that they remain somehow human "readable" (at last for a programmer).
There exist a lot of JSON libraries (notably in C and C++): jansson in C, jsoncpp for C++, etc etc...
Does your scientific instrument runs only a tiny 8 bit controller? If yes, you might be constrained by code size...
And I suggest also to document the serialized format.
序列化 C 结构的最快/最简单的方法是使用 X 宏。这使您可以一起定义相关属性并重用元素。这个例子没有做任何应该做的错误检查,但是如果实现少于 30 行,就很难找到更短的。更精细的用途是可能的,例如自动创建 getter 和 setter。
#include <stdio.h>
#define SETTINGS_TABLE \
X(float, "%f", foo, 2.71818) \
X(float, "%f", bar, 0.70711) \
X(int, "%i", baz, 42)
#define X(type, fmt, name, default) type name ;
struct Settings { SETTINGS_TABLE };
#undef X
#define X(type, fmt, name, default) default ,
struct Settings settings = { SETTINGS_TABLE };
#undef X
void dump(FILE *f)
{
#define X(type, fmt, name, default) fprintf(f, "%s=" fmt "\n", #name, settings.name);
SETTINGS_TABLE
#undef X
}
void load(FILE *f)
{
#define X(type, fmt, name, default) fscanf(f, #name "=" fmt, &settings.name);
SETTINGS_TABLE
#undef X
}
int main(int argc, char *argv[])
{
FILE *cfg;
cfg = fopen(argv[1], "r");
load(cfg);
fclose(cfg);
dump(stdout);
return 0;
}