문제

내가 노력하고 분석 INI 파일을 사용하여 C++.모든 끝에 가장 좋은 방법이 무엇인 이를 달성하기 위해?를 사용해야 하 Windows API 위한 도구를 INI 파일을 처리(으로 나는 완전히 익숙하지 않은),오픈 소스 솔루션 또는 시도를 분석합니다.

도움이 되었습니까?

해결책

당신이 사용할 수 있습 Windows API 함수,등 GetPrivateProfileString()거의 가리키().

다른 팁

필요하신 경우 크로스-플랫폼 솔루션도 향상의 프로그램 옵션 라이브러리입니다.

나는 결코 분석 ini 파일은,그래서 나는 할 수 없습이 너무 특정에서 이 문제를 해결합니다.
그러나 나는 하나의 조언:
지 않는 휠로 기존 요구 사항을 충족하

http://en.wikipedia.org/wiki/INI_file#Accessing_INI_files
http://sdl-cfg.sourceforge.net/
http://sourceforge.net/projects/libini/
http://www.codeproject.com/KB/files/config-file-parser.aspx

행운을 빕니다:)

내가 사용하는 SimpleIni.그것은 크로스-플랫폼입니다.

이미 사용하고 있는 경우에는 Qt

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

다음 값을 읽

my_settings.value("GroupName/ValueName", <<DEFAULT_VAL>>).toInt()

의 무리가 있 다른 변환하는 변환 INI 값으로 모두 표준 형태 및 Qt 형식입니다.보 Qt documentation QSettings 자세한 내용은.

이 질문은 약간 오래된하지만,나는 나의 대답이다.내가 테스트는 다양한 INI 클래스(당신이 그들을 볼 수 있습니다에 나 웹사이트 고)내가 또한 사용 simpleIni 기 때문에 내가 하고 싶은 일을 하 INI 파일에는 모두 windows 합니다.창의 GetPrivateProfileString()에서만 작동합 레지스트리에서 주춤입니다.

그것은 매우 쉽게 읽으로 simpleIni.다음 예를 참고하십시오.

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

inih 간단한 ini 파서에 기록 C,그 C++래퍼 too.를 들어 사용:

#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";

저자는 또한 목록의 기존 라이브러리 .

을 시도했다 게 됩;매우 JSON 오래되지 않았습니다.나는 그것을 선호 XML configuration files.

에 관심이 있다면 플랫폼은 휴대성,시도할 수 있습니다.PropertyTree.그것은 지원 ini 로 persistancy 형식은,하지만산 트리 나의 1 수준의 깊은니다.

계획이 없다면 응용 프로그램 크로스-플랫폼을 사용하여 Windows API 를 호출 할 수있는 가장 좋은 방법이 될 것이다.그냥 무시하고 노트에서는 API 를 설명서에 대해서만 제공됩 16-비트 응용 프로그램의 호환성이다.

아니면 늦게 대답만,알고 가치가 있습니다.필요한 경우 크로스-플랫폼 솔루션을 확실히 시도할 수 있는 특별한 파일은,그것의 재미있게 배울 수 있습니다.(https://developer.gnome.org/glib/stable/glib-Key-value-file-parser.html)

이 질문은 아주 오래된,그러나 나는 그것 때문에 나는 뭔가가 필요 크로스 플랫폼 linux,win32...내가 쓴 아래의 기능,그것은 하나의 기능을 분석한 INI 파일,다른 사람들이 그것을 찾을 유용합니다.

규칙 및 주의 사항:buf 을 분석해야 합 NULL 종료 문자열입니다.부하 ini 파일로 char 배열의 문자열 및 이 함수를 호출하는 구문 분석합니다.섹션의 이름이 있어야 합[]괄호는 주위에,그들은 이와 같은[MySection],또한 값과 섹션에 선지 않는 공간이 있습니다.그 파일을 구문 분석 Windows 또는 리눅스 라인 엔딩이 있습니다.댓글을 사용해야#나//고 상단에서 시작하는 파일의 코멘트와 혼합해야 INI 항목 데이터입니다.따옴표 및 진드기질 모두에서 끝나는 반환의 문자열입니다.공간만 손질하는 경우 그들은 외부의 견적입니다.문자열은 필요하지 않습니다 따옴표,그리고 공백질이다면 따옴표는 없습니다.추출할 수도 있습니다 숫자 또는 기타 데이터,예를 들어,당신은 플로트를 수행하는 atof(ret)에 ret 버퍼입니다.

//  -----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
}

내가 사용하여 종료 inipp 는 언급되지에서 스레드가 있습니다.

https://github.com/mcmtroffaes/inipp

었 MIT 라이센스 헤더만을 구현하는 간단하는 추가 프로젝트 및 4 개의 라인을 사용합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top