【发布时间】:2017-05-31 12:38:12
【问题描述】:
在 CPP Visual Studio 2010 中。我需要从 ini 文件中读取一些配置。下面的代码不起作用。谁能帮我修一下。
char * path = "C:\\NotBackedUp\\Workspaces\\LDAP-DLL\\LDAPTestApp\\bin\\Debug\\conf\\ldap.ini";
std::wcout << "path: " << path << std::endl;
if(!ATLPath::FileExists(path))
{
HRESULT hr = ATL::AtlHresultFromLastError();
ATLTRACE("%x\n",hr);//system could not find the file specified!
std::cout << "File not found " << std::endl;
return 0;
}
else
{
std::cout << "File found " << std::endl;
}
char valueRead[320];
int a = GetPrivateProfileStringA("ldap", "url", "error", valueRead, 320, path);
std::cout << "Value Read " << valueRead << std::endl;
std::cout << "Error String " << GetLastErrorAsString();
上面的代码正在生成下面的日志,你可以看到 ATLPath::FileExists 返回 true,但 getLastError 仍然表明系统找不到指定的文件
path: C:\NotBackedUp\Workspaces\LDAP-DLL\LDAPTestApp\bin\Debug\conf\ldap.ini
File found
Value Read error
Error String The system cannot find the file specified.
我的 ldap.ini 文件有以下几行,可在上述路径中找到
[ldap]
url=ldap://testserver
非常感谢任何帮助
谢谢
【问题讨论】:
-
GetPrivateProfileString仅用于 16 位兼容性,应避免使用,如果您需要所有用户共享配置,请考虑使用注册表或配置文件。 -
如documentation 中所说:
Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.。也许您不应该将信息存储在 ini 文件中,而应存储在注册表中。或者编写你自己的 ini 文件解析器,因为这个 WinAPI 函数已被弃用。 -
函数成功(从某种意义上说,它返回了一个有效的字符串)。成功后调用
GetLastError将返回垃圾。即使它失败了,你打电话给GetLastError也太晚了。你在调用GetPrivateProfileStringA和调用GetLastError之间做了很多其他事情,其中任何一个都可能重置GetLastError。 -
您努力使用完整的路径名。但是你不使用它,只将“ldap”传递给函数。而不是
path。当前工作目录设置正确的几率总是很低,当你问这样的问题时为零。使用path。 -
@Andre Kampling,如果只是为了向后兼容,那么他们为什么要增强 api 以支持 unicode 字符。在 WinBase.h 中,您会看到这一行 #ifdef UNICODE #define GetPrivateProfileString GetPrivateProfileStringW #else #define GetPrivateProfileString GetPrivateProfileStringA #endif // !UNICODE