You can pass NULL
in lpString
of WritePrivateProfileString
to delete the key pointed to by the lpKeyName
parameter and then write again. It‘s documented for WritePrivateProfileString
to not delete existing data.
Error in WritePrivateProfileString function when just writing space characters
Hello,
when using the following code to 10x write a single space into an ini-file, the corresponding entry in that file contains 10 spaces.
#include <windows.h>
#include <cassert>
int main()
{
for(int i = 0; i < 10; ++i)
{
const BOOL bRet = WritePrivateProfileStringA("Section", "SingleSpace", " ", "C:\\TEMP\\iniFileTest.ini");
assert(bRet);
}
//const BOOL bRet = WritePrivateProfileStringA("Section", "SingleSpace", "Hello World", "C:\\TEMP\\iniFileTest.ini");
//assert(bRet);
return 0;
}
When you uncomment lines 10 and 11 in the code sample and run the program again the corresponding "SingleSpace" entry in the ini-file contains "Hello World", followed by 10 spaces. (Provided that you deleted the "SingleSpace"-key in the ini-file before, otherwise its 20 spaces.)
I found no possibility to remove that trailing spaces using WritePrivateProfileString except deleting the whole key and inserting it again. But this will change the order in the ini file.
So it looks that WritePrivateProfileString has a problem with trailing spaces. Any chance that this "unexpected" behavior will be fixed? Or is there a different workaround? (Unfortunately it is not an option to write the key-value pairs to registry or use a different format (like XML or JSON) for storing them.)
For my application I actually use a trim-right function before writing to the ini-file but when there are already trailing spaces in an entry they will remain forever (or until the user removes them by hand).
The code sample was run with Visual Studio Professional 2017 version 15.9.39 using the corresponding C++ compiler and latest Windows-SDK version (10.0.17763.0).
Best regards
Holger Farr
Windows development | Windows API - Win32
1 answer
Sort by: Most helpful
-
Xiaopo Yang - MSFT 12,731 Reputation points Microsoft External Staff
2021-10-06T05:24:34.97+00:00