我做了一个INI文件解析器,它在Windows上运行良好,但在Linux上运行良好,问题来自memcmp函数,它不应该返回0,我已经用printf和strlen检查过,(我也试过用strncmp相反,它返回了不同的值,但仍然不同于 0),但找不到问题出在哪里。
这是代码:
#define INI_KEY_LENGTH 128
#define BEGIN '['
#define SEP '='
#define COMMENT ';'
static char configfilename[255];
static char * str_dup (const char * str){
char * dup = NULL;
if (str != NULL){
size_t size = strlen (str) + 1;
dup = malloc (size);
if (dup != NULL){
memcpy (dup, str, size);
}
}
return dup;
}
static void str_finalize (char * str){
char * p = strchr (str, '\n');
if (p != NULL){
*p = '\0';
}
}
static char * get (const char * filename, const char * section, const char * key){
char * ret = NULL;
char buff [INI_KEY_LENGTH];
FILE * file = NULL;
int opened = 0;
file = fopen (filename, "r");
if (file != NULL){
while ((fgets (buff, INI_KEY_LENGTH, file)) != NULL){
str_finalize (buff);
if (! opened && buff [0] == BEGIN){
char * p = buff;
// Don't work here
if (memcmp (p + 1, section, strlen (buff) - 2) == 0){
opened = 1;
continue;
}
}
else if (opened){
if (buff [0] == BEGIN){
opened = 0;
break;
}
if(buff [0] != COMMENT){
if (strstr (buff, key) != NULL){
char * p = strchr (buff, SEP);
if (p != NULL){
p++;
ret = str_dup (p);
break;
}
}
}
}
}
fclose (file);
}
return ret;
}
int init_iniFile (const char * filename){
int ret = 0;
FILE * file;
if ((file = fopen(filename, "r")) != NULL){
fclose(file);
strcpy(configfilename, filename);
ret = 1;
}
return ret;
}
char * get_string (const char * section, const char * key){
return get (configfilename, section, key);
}
我怀疑这个错误很愚蠢,但我是 C 的菜鸟,很抱歉给您带来不便。