繁体   English   中英

在C中使用fscanf读取ini文件

[英]reading ini files using fscanf in c

我在解析.ini file遇到问题。 我知道有很多关于该主题的文章,并且我已经阅读了很多。 我的ini file只有一个entry

font=tahoma.ttf

源代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static FILE *ini_file;
char font[20];

void LoadConfig()
{
    char Setting[20],Value[20];
    int EndOfFile = 0;
    if ((ini_file = fopen("config.ini", "r")))
    {
        EndOfFile = fscanf(ini_file, "%[^=]=%s", Setting, &Value);
        while (EndOfFile != EOF)
        {
            if(strcmp(Setting,"font") == 0)
            {
                strcpy(font,Value);
            }
            EndOfFile = fscanf(ini_file, "%[^=]=%s", Setting, &Value);
        }
        fclose(ini_file);
    }
}

问题在于,该值永远不会读入font variable

SefFault可能是由&之前的值引起的,但是即使删除了if,您仍然可以读取超过20个字符的 而且某些ini文件可能包含不遵循该模式的注释行,并且会破坏您的程序

您确实应该:

  • fgets逐行读取至少255个字符的缓冲区-重复直到文件结尾: while (NULL != fgets(line, sizeof(line), stdin)) { ...}
  • 使用sscanf解析每一行并忽略每一个不符合要求的行:

     if (2 == sscanf(line, "%19[^=]=%19s", Setting, Value) { ... } 

使用fgets读取文件中的每一行。 strpbrk可用于查找等号和换行符,并将该范围的字符复制到变量中。

void LoadConfig()
{
    char Setting[100] = {'\0'},Value[100] = {'\0'}, line[300] = {'\0'};
    size_t span = 0;
    if ((ini_file = fopen("config.ini", "r")))
    {
        while ( fgets ( line, sizeof ( line), ini_file))//read each line
        {
            char *equal = strpbrk ( line, "=");//find the equal
            if ( equal)//found the equal
            {
                span = equal - line;
                memcpy ( Setting, line, span);
                Setting[span] = '\0';
                if(strcmp(Setting,"font") == 0)
                {
                    equal++;//advance past the =
                    char *nl = strpbrk ( equal, "\n");//fine the newline
                    if ( nl)//found the newline
                    {
                        span = nl - equal;
                        memcpy ( font, nl, span);
                        font[span] = '\0';
                    }
                }
            }
        }
        fclose(ini_file);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM