[英]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.