簡體   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