CPP-基础:c++读取ini文件

配置文件格式是
[JP]
K=2EC156673E 2F4240 5595F6

char str[50];
GetPrivateProfileString("JP", "K",NULL, str, sizeof(str),".\\keydog.ini");
得到str后想将其分成三个字符串
str1=2EC156673E
str2=2F4240
str3=5595F6

第一种方法用MFC 
得有这句#include <afx.h>和包含mfc库

CString sz;
GetPrivateProfileString("JP", "K", NULL, sz.GetBuffer(50), 50, "./keydog.ini");
sz.ReleaseBuffer();
int nPos = 0;
CString sz1, sz2, sz3;
sz1 = sz.Tokenize(" ", nPos);
sz2 = sz.Tokenize(" ", nPos);
sz3 = sz.Tokenize(" ", nPos);

第二种用标准c++
得#include <string> 和using std::string;

string str(50, 0);
GetPrivateProfileString("JP", "K", NULL, (char*)str.c_str(), 50, "./keydog.ini");
string sz1, sz2, sz3;
int nBegin = 0, nEnd = str.find(' ', nBegin);
sz1 = str.substr(nBegin, nEnd - nBegin);
nBegin = nEnd + 1, nEnd = str.find(' ', nBegin);
sz2 = str.substr(nBegin, nEnd - nBegin);
nBegin = nEnd + 1, nEnd = str.find(' ', nBegin);
sz3 = str.substr(nBegin, nEnd - nBegin);

第三种纯c吧...
得#include <string.h>

char str[50] = {0};
GetPrivateProfileString("JP", "K", NULL, str, sizeof(str),".\\keydog.ini");
char sz1[50] = {0}, sz2[50] = {0}, sz3[50] = {0};
sscanf( str, "%[^' ']", sz1);
sscanf( str + strlen(sz1) + 1, "%[^' ']", sz2);
sscanf( str + + strlen(sz1) + strlen(sz2) + 2, "%[^' ']", sz3);

再给个傻瓜版c代码吧, 因为str1等没有另外给空间, 看你怎么用了
#include <stdio.h>
#include <windows.h>

int main()
{
char str[50], *str1, *str2, *str3;
GetPrivateProfileString("JP", "K",NULL, str, sizeof(str),".\\keydog.ini");
str2 = str1 = str;
while( ' ' != *++str2);
*str2++ = 0;
for( str3 = str2; ' ' != *++str3; );
*str3++ = 0;

return 0;
}
posted @ 2013-12-10 09:55  CPYER  阅读(743)  评论(0编辑  收藏  举报