我正在编写一个简单的解析器来读取配置文件.config.h接口只有三个主要功能,简要如下,
config_init();
config_dinit();
config_parse();
config_read_value();
Run Code Online (Sandbox Code Playgroud)
我的问题是那些函数会发出不同类型的错误,例如,
config_init() emit , FILE_NOT_FOUND,FILE_EOF_ERROR,FILE_OPEN_ERROR, ...
config_dinit() emit , NOT_INIT_ERROR ,
config_parse() emit , PARSE_ERROR, OVERFLOW_ERROR, INVALID_CHARACTER_FOUND_ERROR,...
config_read_value() emit, SECTION_NOT_FOUND,KEYWORD_NOT_FOUND,OVERFLOW_ERROR,NOT_INITIALIZED_ERROR,INVALID_STATE_ERROR,... etc.
Then I create enums for each function, for by using these names ,
enum Config_ParseError{...} , enum Config_InitError{...} ,enum Config_ReadValueError{..}
etc.
Run Code Online (Sandbox Code Playgroud)
一些枚举值相互重叠,也会出现"编译错误".喜欢OVERFLOW_ERROR,
我正在打开你的建议,
我已经对谷歌进行了快速研究,发现最流行的IRC客户端源代码定义了这样的枚举,
enum {
CMDERR_OPTION_UNKNOWN = -3, /* unknown -option */
CMDERR_OPTION_AMBIGUOUS = -2, /* ambiguous -option */
CMDERR_OPTION_ARG_MISSING = -1, /* argument missing for -option */
CMDERR_UNKNOWN, /* unknown command */
CMDERR_AMBIGUOUS, /* ambiguous command */
CMDERR_ERRNO, /* get the error from errno */
CMDERR_NOT_ENOUGH_PARAMS, /* not enough parameters given */
CMDERR_NOT_CONNECTED, /* not connected to server */
CMDERR_NOT_JOINED, /* not joined to any channels in this window */
CMDERR_CHAN_NOT_FOUND, /* channel not found */
CMDERR_CHAN_NOT_SYNCED, /* channel not fully synchronized yet */
CMDERR_ILLEGAL_PROTO, /* requires different chat protocol than the active server */
CMDERR_NOT_GOOD_IDEA, /* not good idea to do, -yes overrides this */
CMDERR_INVALID_TIME, /* invalid time specification */
CMDERR_INVALID_CHARSET, /* invalid charset specification */
CMDERR_EVAL_MAX_RECURSE, /* eval hit recursion limit */
CMDERR_PROGRAM_NOT_FOUND /* program not found */
};
Run Code Online (Sandbox Code Playgroud)
它定义了没有任何名字的枚举,这是一个好的风格吗?那为什么原因是什么?
真的需要一些更好的命名决定.请不要伤害我,我只是开始阅读"写漂亮的C代码"一书.
提前致谢.三墩.
use*_*116 22
我通常是整个库的一组错误返回的粉丝.这种方式在消费者中他们不必担心"输入X的输入是-1还是无法连接到Y".
我也是E_前缀的粉丝,但实际上任何人都会做:
enum _config_error
{
E_SUCCESS = 0,
E_INVALID_INPUT = -1,
E_FILE_NOT_FOUND = -2, /* consider some way of returning the OS error too */
....
};
/* type to provide in your API */
typedef enum _config_error error_t;
/* use this to provide a perror style method to help consumers out */
struct _errordesc {
int code;
char *message;
} errordesc[] = {
{ E_SUCCESS, "No error" },
{ E_INVALID_INPUT, "Invalid input" },
{ E_FILE_NOT_FOUND, "File not found" },
....
};
Run Code Online (Sandbox Code Playgroud)