【问题标题】:GetPrivateProfileStringA is returning "The system cannot find the file specified." eventhough the file existsGetPrivateProfileString 正在返回“系统找不到指定的文件。”即使文件存在
【发布时间】: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

标签: c++ ini


【解决方案1】:

当 GetPrivateProfileString 无法找到部分或值时,也会设置您得到的 ERROR_FILE_NOT_FOUND 错误代码。

您的代码在我的 Win10 上使用您的 ini 文件运行良好。

使用十六进制查看器/编辑器验证您的 ldap.ini 实际上是 ASCII,并且它不包含 BOM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2016-12-20
    • 2013-11-21
    • 2023-03-17
    相关资源
    最近更新 更多