gpt4 book ai didi

c - 在c中使用fscanf读取ini文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:15 25 4
gpt4 key购买 nike

我在解析 .ini 文件 时遇到问题。我知道有很多关于这个主题的帖子,我已经阅读了其中的很多。我的 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 可能是由 Value 之前的 & 引起的,但即使在删除 if 之后,您仍然可以读取超过 20 个字符的 value。并且某些 ini 文件可能包含不遵循该模式的注释行,并且会破坏您的程序

你真的应该:

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

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

关于c - 在c中使用fscanf读取ini文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37443685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com