C++을 사용하여 INI 파일을 구문 분석하려고합니다. 이것을 달성하는 가장 좋은 방법은 무엇입니까? INI 파일 처리 (완전히 생소한), 오픈 소스 솔루션 또는 수동으로 구문 분석하려는 Windows API 도구를 사용해야합니까?C++에서 INI 파일을 구문 분석하는 가장 쉬운 방법은 무엇입니까?
답변
Windows API 함수 인 suc를 사용할 수 있습니다. h를 GetPrivateProfileString() 및 GetPrivateProfileInt()으로 설정합니다.
필자는 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
행운을 빕니다 :)
을 충족하는가 한 바퀴를 재발견하지 마십시오
하지만 난 한 조언을
크로스 플랫폼 앱을 만들 계획이 아니라면 Windows API 호출을 사용하는 것이 가장 좋은 방법입니다. 16 비트 앱 호환성 만 제공된다는 API 문서의 메모는 무시하십시오.
크로스 플랫폼 솔루션이 필요한 경우 Boost의 Program Options 라이브러리를 사용해보십시오.
이 라이브러리도 좋습니다 – varnie
이것이 방법입니다. 사람들이 왜 그렇게 많이 투표하지 않는지 이해하지 못합니다. –
@Gollum, 그것은 주어진 종속성이 Windows처럼 들립니다. 프로그램 옵션 라이브러리 사용은 다른 종속성을 취하는 것을 의미합니다. 가끔 큰 문제가 아니며 때로는 그렇습니다. –
시도해 보셨습니까 libconfig; 매우 JSON 같은 구문. XML 구성 파일보다 선호합니다.
이 질문은 다소 오래되었지만 답변을 게시 할 예정입니다. 여러 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);
이미 다음 값을 읽어
QSettings my_settings("filename.ini", QSettings::IniFormat);
Qt는
를 사용하는 경우 모두로 INI 값을 변환 다른 컨버터의 무리가 있습니다my_settings.value("GroupName/ValueName", <<DEFAULT_VAL>>).toInt()
표준 유형 및 Qt 유형. 자세한 내용은 QSettings의 Qt 설명서를 참조하십시오.
변경 사항을 저장하면 다시 저장됩니다. ini 파일을 말하지 않고 (예 : 소멸자가'sync()'를 호출합니다. 이것은 깜짝 할 수 있습니다) 그리고 변수가 이전에 정의 된 주석과 순서를 파괴합니다 ... –
플랫폼 이식성에 관심이있는 경우 Boost.PropertyTree를 사용해 볼 수도 있습니다. 그것은 ini를 지속성 형식으로 지원합니다. 속성 트리는 1 단계 만 가능합니다.
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의 목록이 있습니다.
아마 늦은 answer..But, 당신은 크로스 플랫폼 솔루션을 필요로 options..If 아는 가치, 확실히 당신이 .. (https://developer.gnome.org/glib/stable/glib-Key-value-file-parser.html)
나는 알고이 질문은 매우 흥미 롭다는 ,, 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
}
- 1. ActionScript3/Flex에서 XML을 구문 분석하는 가장 쉬운 방법은 무엇입니까?
- 2. 웹 사이트의 HTML을 구문 분석하는 가장 빠르고 쉬운 방법은 무엇입니까?
- 3. XML을 구문 분석하는 가장 빠른 방법은 무엇입니까?
- 4. nagios status.dat 파일을 구문 분석하는 방법은 무엇입니까?
- 5. 로그 파일을 파이썬 목록으로 구문 분석하는 가장 좋은 방법은 무엇입니까?
- 6. 이 파일을 구문 분석하는 가장 좋은 방법은 무엇입니까?
- 7. Json을 구문 분석하는 가장 좋은 방법은 무엇입니까?
- 8. 텍스트를 구문 분석하는 가장 빠른 방법은 무엇입니까?
- 9. Bash에서 CSV 파일을 구문 분석하는 방법은 무엇입니까?
- 10. PHP로 .plist 파일을 구문 분석하는 방법은 무엇입니까?
- 11. 속성이있는 XML 파일을 구문 분석하는 방법은 무엇입니까?
- 12. JavaScript로 Excel 파일을 구문 분석하는 방법은 무엇입니까?
- 13. .msstyles 파일을 구문 분석하는 방법은 무엇입니까?
- 14. Java에서 .plist 파일을 구문 분석하는 방법은 무엇입니까?
- 15. 이 OFX 파일을 구문 분석하는 방법은 무엇입니까?
- 16. SSIS에서 XML 파일을 구문 분석하는 방법은 무엇입니까?
- 17. XSD 파일을 구문 분석하는 방법
- 18. DOC 파일을 생성하는 가장 쉬운 방법은 무엇입니까?
- 19. 파일을 구문 분석하는 도구
- 20. Youtube 검색 결과를 구문 분석하는 방법은 무엇입니까?
- 21. RSS 피드를 결합하고 구문 분석하는 방법은 무엇입니까?
- 22. sscanf()를 사용하여 c에서 URL을 구문 분석하는 방법은 무엇입니까?
- 23. C에서 필드를 구분하는 따옴표로 CSV를 구문 분석하는 방법은 무엇입니까?
- 24. C에서 datetime 구조체로 문자열을 구문 분석하는 방법은 무엇입니까?
- 25. Python을 사용하여 VisualStudio .csproj 파일을 구문 분석하는 가장 좋은 방법
- 26. PHP로 HTML을 구문 분석하는 방법은 무엇입니까?
- 27. PHP 클래스에서 ".ini"파일을 호출하는 방법은 무엇입니까?
- 28. Java에서 다중 행 SQL 문을 구문 분석하는 가장 쉬운 방법은 무엇입니까?
- 29. Obj-C에서 객체 통신을 설정하는 가장 쉬운 방법은 무엇입니까?
- 30. Python을 사용하여 주석 파일의 .h 파일을 구문 분석하는 쉬운 방법은 무엇입니까?
GetPrivateProfileInt() 및 기타 기능은, MSDN에 의해 권장하지 않습니다 16 비트 시스템 대신 다른 접근 방식을 사용하십시오. https://msdn.microsoft.com/en-us/library/windows/desktop/ms724345(v=vs.85).aspx –