gpt4 book ai didi

winapi - GetPrivateProfileString - 缓冲区长度

转载 作者:行者123 更新时间:2023-12-03 00:42:42 31 4
gpt4 key购买 nike

Windows 的 GetPrivateProfileXXX 函数(用于处理 INI 文件)在处理缓冲区长度方面有一些奇怪的规则。

GetPrivateProfileString 的文档指出:

If [..] the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.

我读了这篇文章,我意识到这种行为使得无法区分代码中的两种场景:

  • 当值字符串的长度恰好等于 nSize - 1 时。
  • 当nSize值(即缓冲区)太小时。

我想我应该尝试一下:

我在 INI 文件中有这个:

[Bar]
foo=123456

我使用这些参数调用 GetPrivateProfileString 作为测试:

// Test 1. The buffer is big enough for the string (16 character buffer).
BYTE* buffer1 = (BYTE*)calloc(16, 2); // using 2-byte characters ("Unicode")
DWORD result1 = GetPrivateProfileString(L"Bar", L"foo", NULL, buffer, 16, fileName);

// result1 is 6
// buffer1 is { 49, 0, 50, 0, 51, 0, 52, 0, 53, 0, 54, 0, 0, 0, 0, 0, ... , 0, 0 }

// Test 2. The buffer is exactly sufficient to hold the value and the trailing null (7 characters).
BYTE* buffer2 = (BYTE*)calloc(7, 2);
DWORD result2 = GetPrivateProfileString(L"Bar", L"foo", NULL, buffer, 7, fileName);

// result2 is 6. This is equal to 7-1.
// buffer2 is { 49, 0, 50, 0, 51, 0, 52, 0, 53, 0, 54, 0, 0, 0 }

// Test 3. The buffer is insufficient to hold the value and the trailing null (6 characters).
BYTE* buffer3 = (BYTE*)calloc(6, 2);
DWORD result3 = GetPrivateProfileString(L"Bar", L"foo", NULL, buffer, 6, fileName);

// result3 is 5. This is equal to 6-1.
// buffer3 is { 49, 0, 50, 0, 51, 0, 52, 0, 53, 0, 0, 0 }

调用此代码的程序无法确定实际键值的长度是否确实是 5 个字符,甚至是 6 个字符,因为在最后两种情况下结果等于 nSize - 1。

唯一的解决方案是在 result == nSize - 1 时进行检查,并使用更大的缓冲区调用该函数,但在缓冲区大小完全正确的情况下,这是不必要的。

有没有更好的办法?

最佳答案

没有更好的办法了。只需尝试确保第一个缓冲区足够大即可。任何解决此问题的方法都必须使用文档中未描述的内容,因此无法保证有效。

关于winapi - GetPrivateProfileString - 缓冲区长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10507927/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com