Click to See Complete Forum and Search --> : Help reading ini file
MagniB
July 6th, 2010, 11:33 PM
Hello,
I am trying to read a ini file but having some problems.
Suppose I have a ini file, "infoDat.ini". It contains:
[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:
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!!!
ahmd
July 7th, 2010, 03:14 AM
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 (http://msdn.microsoft.com/en-us/library/ms724360%28v=VS.85%29.aspx), don't you?
Igor Vartanov
July 7th, 2010, 04:11 AM
From MSDN (http://msdn.microsoft.com/en-us/library/ms724345(VS.85).aspx)
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.
Igor Vartanov
July 7th, 2010, 04:22 AM
The cure:
#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;
}
MagniB
July 7th, 2010, 10:38 PM
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.
MagniB
July 7th, 2010, 10:46 PM
Nope, Igor's code is also giving "id = -1". lol why is this happening?
MagniB
July 7th, 2010, 11:01 PM
Ok, got it. Finally it worked. I needed to keep the ini file in Debug folder. lol
Igor Vartanov
July 8th, 2010, 03:39 AM
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.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.