-
July 6th, 2010, 11:33 PM
#1
Help reading ini file
Hello,
I am trying to read a ini file but having some problems.
Suppose I have a ini file, "infoDat.ini". It contains:
Code:
[Guy]
name=Magni
id=5
[Girl]
name=Sarah
id=6
Now I am trying to read "id" key from section "Guy", here's what I did:
Code:
int getID;
getID = GetPrivateProfileInt("Guy", "id", -1, "infoDat.ini");
Now the problem is, the function always return -1. Why is that? Isn't it suppose to return 5?
Please help me!!!
-
July 7th, 2010, 03:14 AM
#2
Re: Help reading ini file
You get your default value specified in the 3rd parameter in the call to GetPrivateProfileInt(). Most certainly the "infoDat.ini" file is not properly formatted, or it cannot be located by a relative path. To remedy specify a full file path in the lpFileName parameter.
PS. You realize that GetPrivateProfileInt() API was deprecated in favor of the System Registry APIs, don't you?
-
July 7th, 2010, 04:11 AM
#3
Re: Help reading ini file
From MSDN
lpFileName [in]
The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
Best regards,
Igor
-
July 7th, 2010, 04:22 AM
#4
Re: Help reading ini file
The cure:
Code:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
BOOL MakeFilePathNextToMe(LPCTSTR fileName, LPTSTR outPath, DWORD cchPath)
{
if (GetModuleFileName(NULL, outPath, cchPath))
{
LPTSTR p = _tcsrchr(outPath, TEXT('\\'));
if (p)
{
_tcscpy(p + 1, fileName);
return TRUE;
}
}
return FALSE;
}
int _tmain()
{
int getID;
TCHAR iniPath[MAX_PATH] = {0};
if (!MakeFilePathNextToMe(TEXT("infoDat.ini"), iniPath, COUNTOF(iniPath)))
{
return -1;
}
getID = GetPrivateProfileInt(TEXT("Guy"), TEXT("id"), -1, iniPath);
_tprintf(TEXT("id = %d\n"), getID);
return 0;
}
Best regards,
Igor
-
July 7th, 2010, 10:38 PM
#5
Re: Help reading ini file
I did try and specify the full path but didn't work. And I also know GetPrivateProfileInt() API was deprecated in favor of the System Registry APIs, but in this situation, I have to use ini file.
I will try Igor's code and see what happens.
-
July 7th, 2010, 10:46 PM
#6
Re: Help reading ini file
Nope, Igor's code is also giving "id = -1". lol why is this happening?
-
July 7th, 2010, 11:01 PM
#7
Re: Help reading ini file
Ok, got it. Finally it worked. I needed to keep the ini file in Debug folder. lol
-
July 8th, 2010, 03:39 AM
#8
Re: Help reading ini file
You need to keep .ini file next to your executable wherever it is, Debug folder in case you run Debug build from VS IDE. I thought it'd easy to get from the source.
Best regards,
Igor
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|