【发布时间】:2015-05-02 07:36:10
【问题描述】:
所以,我需要访问一个 .ini 文件,例如:
[alpha]
colour=green
size=78
style=italic
[beta]
colour=black
size=94
mode=xyz
[gamma]
black=0231
blue=127
red=0x35876f
我需要找到一个部分 [likethis],然后是一个参数(以下三个之一),然后返回它的值。所以,部分 alpha,参数大小,我返回“78”。部分 gamma,param red,我返回“0x35876f”。部分 beta,参数 red 不存在。
char *sFile: Name of file
char *sSec: Section where the parameter is
char *sPar: Parametro wanted
char *sRet: Array where I store the value
int ilen: Lenght of the array
我用fp = fopen (sFile,"r"); 打开文件,但是查找和返回值变得很复杂,我不知道这是否是最好的方法。
char *strAux, *strAux2;
while(!feof(fp)) //While the file doesnt end
{
fscanf (fp,"%s",strAux); //Read a line of the file
if(!strcmp(strAux,sSec)) //If I found the section
{
for(j=0; j<3; j++)
{
fscanf(fp,"%s",strAux); //Read a line
strAux2 = strtok (strAux,"="); //store the param in strAux2 from the start to the =
if (!strcmp(strAux2,sPar))
{
strAux2 = strtok (NULL,"\r\n"); //store in strAux2 frmo the = to end of line
if(strlen(strAux2)>ilen)
{
fclose(fp);
return (-3); //Error, Lenght Value > ilen
}else{
strncpy(sRet,strAux2,ilen);
fclose(fp);
return (sRet); //Return the value
}
}
}
}
}
fclose(fp);
return (-2); //Error, Parameter not found
这样好吗?
【问题讨论】:
-
"I" 是 SHIFT 的英文!不,不,“我”!
-
请参阅
while (!feof(file))is always wrong,了解为什么您的代码从一开始就是可疑的。在尝试使用strAux变量之前,您必须检查来自fscanf()的返回值。你需要分配内存来读取字符串。 -
您的函数在成功时返回
char *,但在失败时返回各种负数。也就是说,充其量是一个令人讨厌的界面。你最好总是返回一个整数——0 表示成功,负数表示失败。由于sRet似乎是函数的输入参数,因此无需返回它来表示成功。