2008-08-15 6 views

답변

106

Windows API 함수 인 suc를 사용할 수 있습니다. h를 GetPrivateProfileString()GetPrivateProfileInt()으로 설정합니다.

+0

GetPrivateProfileInt() 및 기타 기능은, MSDN에 의해 ​​권장하지 않습니다 16 비트 시스템 대신 다른 접근 방식을 사용하십시오. https://msdn.microsoft.com/en-us/library/windows/desktop/ms724345(v=vs.85).aspx –

2

크로스 플랫폼 앱을 만들 계획이 아니라면 Windows API 호출을 사용하는 것이 가장 좋은 방법입니다. 16 비트 앱 호환성 만 제공된다는 API 문서의 메모는 무시하십시오.

109

크로스 플랫폼 솔루션이 필요한 경우 Boost의 Program Options 라이브러리를 사용해보십시오.

+0

이 라이브러리도 좋습니다 – varnie

+18

이것이 방법입니다. 사람들이 왜 그렇게 많이 투표하지 않는지 이해하지 못합니다. –

+15

@Gollum, 그것은 주어진 종속성이 Windows처럼 들립니다. 프로그램 옵션 라이브러리 사용은 다른 종속성을 취하는 것을 의미합니다. 가끔 큰 문제가 아니며 때로는 그렇습니다. –

16

나는 SimpleIni을 사용합니다. 그것은 크로스 플랫폼입니다.

+1

은 utf-16을 지원하지 않습니다. (왜 ??? – DiGMi

+0

SimpleIni가 이제 Github에서 호스팅됩니다. –

+1

https://github.com/brofield/simpleini – Katu

4

시도해 보셨습니까 libconfig; 매우 JSON 같은 구문. XML 구성 파일보다 선호합니다.

8

이 질문은 다소 오래되었지만 답변을 게시 할 예정입니다. 여러 INI 클래스 (내 website에서 볼 수 있음)를 테스트했으며 simpleIni를 사용합니다. 왜냐하면 두 창과 winCE에서 INI 파일을 사용하기를 원하기 때문입니다. Window의 GetPrivateProfileString()은 winCE의 레지스트리에서만 작동합니다.

simpleIni로 읽기가 매우 쉽습니다. 다음은 예입니다

#include "SimpleIni\SimpleIni.h"  
CSimpleIniA ini; 
ini.SetUnicode(); 
ini.LoadFile(FileName); 
const char * pVal = ini.GetValue(section, entry, DefaultStr); 
13

이미 다음 값을 읽어

QSettings my_settings("filename.ini", QSettings::IniFormat); 

Qt는

를 사용하는 경우

모두로 INI 값을 변환 다른 컨버터의 무리가 있습니다
my_settings.value("GroupName/ValueName", <<DEFAULT_VAL>>).toInt() 

표준 유형 및 Qt 유형. 자세한 내용은 QSettings의 Qt 설명서를 참조하십시오.

+0

변경 사항을 저장하면 다시 저장됩니다. ini 파일을 말하지 않고 (예 : 소멸자가'sync()'를 호출합니다. 이것은 깜짝 할 수 있습니다) 그리고 변수가 이전에 정의 된 주석과 순서를 파괴합니다 ... –

3

플랫폼 이식성에 관심이있는 경우 Boost.PropertyTree를 사용해 볼 수도 있습니다. 그것은 ini를 지속성 형식으로 지원합니다. 속성 트리는 1 단계 만 가능합니다.

5

inih은 C로 작성된 간단한 ini 파서이므로 C++ 래퍼도 함께 제공됩니다. 사용 예제 :

#include "INIReader.h"  

INIReader reader("test.ini"); 

std::cout << "version=" 
      << reader.GetInteger("protocol", "version", -1) << ", name=" 
      << reader.Get("user", "name", "UNKNOWN") << ", active=" 
      << reader.GetBoolean("user", "active", true) << "\n"; 

저자는 또한 기존의 도서관 here의 목록이 있습니다.

0

나는 알고이 질문은 매우 흥미 롭다는 ,, GLIB을 시도 할 수 있습니다 오래된,하지만 리눅스를위한 크로스 플랫폼이 필요했기 때문에 나왔습니다. win32 ... 아래 함수를 작성했습니다. INI 파일을 구문 분석 할 수있는 단일 함수이며 다른 사람들이 유용하다고 생각합니다.

규칙 &주의 사항 : 구문 분석 할 buf는 NULL로 끝나는 문자열이어야합니다. ini 파일을 char 배열 문자열에로드하고이 함수를 호출하여 파싱합니다. 섹션 이름에는 [MySection]과 같이 대괄호가 있어야하며 값과 섹션은 선행 공백없이 한 행에서 시작해야합니다. Windows \ r \ n 또는 Linux \ n 행 끝으로 파일을 구문 분석합니다. 주석은 # 또는 //을 사용하고 파일의 맨 위에서 시작해야하며 INI 항목 데이터와 주석을 섞어서는 안됩니다. 따옴표와 틱은 반환 문자열의 양쪽 끝에서 제거됩니다. 공백은 따옴표 밖에있는 경우에만 다듬어집니다. 문자열에는 따옴표가 필요하지 않으며 따옴표가 없으면 공백을 삭제합니다. 예를 들어 플로트가 ret 버퍼에서 atof (ret)를 수행하는 경우와 같이 숫자 또는 기타 데이터를 추출 할 수도 있습니다. 그들이 쓸모 아직 나이가 만 baskward 호환성을 제공하기 때문에 ... 예제를 사용하는 방법

// -----note: no escape is nessesary for inner quotes or ticks----- 
// -----------------------------example---------------------------- 
// [Entry2] 
// Alignment = 1 
// LightLvl=128 
// Library  = 5555 
// StrValA = Inner "quoted" or 'quoted' strings are ok to use 
// StrValB = "This a "quoted" or 'quoted' String Value" 
// StrValC = 'This a "tick" or 'tick' String Value' 
// StrValD = "Missing quote at end will still work 
// StrValE = This is another "quote" example 
// StrValF = " Spaces inside the quote are preserved " 
// StrValG = This works too and spaces are trimmed away 
// StrValH = 
// ---------------------------------------------------------------- 
//12oClocker super lean and mean INI file parser (with section support) 
//set section to 0 to disable section support 
//returns TRUE if we were able to extract a string into ret value 
//NextSection is a char* pointer, will be set to zero if no next section is found 
//will be set to pointer of next section if it was found. 
//use it like this... char* NextSection = 0; GrabIniValue(X,X,X,X,X,&NextSection); 
//buf is data to parse, ret is the user supplied return buffer 
BOOL GrabIniValue(char* buf, const char* section, const char* valname, char* ret, int retbuflen, char** NextSection) 
{ 
    if(!buf){*ret=0; return FALSE;} 

    char* s = buf; //search starts at "s" pointer 
    char* e = 0; //end of section pointer 

    //find section 
    if(section) 
    { 
     int L = strlen(section); 
     SearchAgain1: 
     s = strstr(s,section); if(!s){*ret=0; return FALSE;} //find section 
     if(s > buf && (*(s-1))!='\n'){s+=L; goto SearchAgain1;} //section must be at begining of a line! 
     s+=L;             //found section, skip past section name 
     while(*s!='\n'){s++;} s++;        //spin until next line, s is now begining of section data 
     e = strstr(s,"\n[");         //find begining of next section or end of file 
     if(e){*e=0;}           //if we found begining of next section, null the \n so we don't search past section 
     if(NextSection)           //user passed in a NextSection pointer 
     { if(e){*NextSection=(e+1);}else{*NextSection=0;} }  //set pointer to next section 
    } 

    //restore char at end of section, ret=empty_string, return FALSE 
    #define RESTORE_E  if(e){*e='\n';} 
    #define SAFE_RETURN RESTORE_E; (*ret)=0; return FALSE 

    //find valname 
    int L = strlen(valname); 
    SearchAgain2: 
    s = strstr(s,valname); if(!s){SAFE_RETURN;}    //find valname 
    if(s > buf && (*(s-1))!='\n'){s+=L; goto SearchAgain2;} //valname must be at begining of a line! 
    s+=L;             //found valname match, skip past it 
    while(*s==' ' || *s == '\t'){s++;}      //skip spaces and tabs 
    if(!(*s)){SAFE_RETURN;}         //if NULL encounted do safe return 
    if(*s != '='){goto SearchAgain2;}      //no equal sign found after valname, search again 
    s++;             //skip past the equal sign 
    while(*s==' ' || *s=='\t'){s++;}      //skip spaces and tabs 
    while(*s=='\"' || *s=='\''){s++;}      //skip past quotes and ticks 
    if(!(*s)){SAFE_RETURN;}         //if NULL encounted do safe return 
    char* E = s;           //s is now the begining of the valname data 
    while(*E!='\r' && *E!='\n' && *E!=0){E++;} E--;   //find end of line or end of string, then backup 1 char 
    while(E > s && (*E==' ' || *E=='\t')){E--;}    //move backwards past spaces and tabs 
    while(E > s && (*E=='\"' || *E=='\'')){E--;}   //move backwards past quotes and ticks 
    L = E-s+1;            //length of string to extract NOT including NULL 
    if(L<1 || L+1 > retbuflen){SAFE_RETURN;}    //empty string or buffer size too small 
    strncpy(ret,s,L);          //copy the string 
    ret[L]=0;            //null last char on return buffer 
    RESTORE_E; 
    return TRUE; 

    #undef RESTORE_E 
    #undef SAFE_RETURN 
} 

....

char sFileData[] = "[MySection]\r\n" 
"MyValue1 = 123\r\n" 
"MyValue2 = 456\r\n" 
"MyValue3 = 789\r\n" 
"\r\n" 
"[MySection]\r\n" 
"MyValue1 = Hello1\r\n" 
"MyValue2 = Hello2\r\n" 
"MyValue3 = Hello3\r\n" 
"\r\n"; 
char str[256]; 
char* sSec = sFileData; 
char secName[] = "[MySection]"; //we support sections with same name 
while(sSec)//while we have a valid sNextSec 
{ 
    //print values of the sections 
    char* next=0;//in case we dont have any sucessful grabs 
    if(GrabIniValue(sSec,secName,"MyValue1",str,sizeof(str),&next)) { printf("MyValue1 = [%s]\n",str); } 
    if(GrabIniValue(sSec,secName,"MyValue2",str,sizeof(str),0))  { printf("MyValue2 = [%s]\n",str); } 
    if(GrabIniValue(sSec,secName,"MyValue3",str,sizeof(str),0))  { printf("MyValue3 = [%s]\n",str); } 
    printf("\n"); 
    sSec = next; //parse next section, next will be null if no more sections to parse 
} 
관련 문제