WritePrivateProfileString is not adding property to the end

蹲街弑〆低调 提交于 2019-12-11 02:09:03

问题


I am writing some properties in a ini file using WritePrivateProfileString function and everything works fine but when I add text with multiple lines, there is a problem.

Here is the code and output.

WritePrivateProfileString(_T("General"), _T("Name"), OLE2CT(text), FilePath);

Output:

[General]
Name=mytext

.

text = address\nstreet\nhouse
WritePrivateProfileString(_T("General"), _T("Address"), OLE2CT(text), FilePath);

Output:

[General]
Name=mytext
Address=address
street
house

But when after adding a multiple line item, i add another item, instead of adding this to end it adds new line just after Address line

text = city
WritePrivateProfileString(_T("General"), _T("City"), OLE2CT(text), FilePath);

Output:

[General]
Name=mytext
Address=address
City=city
street
house

but the output should be

[General]
Name=mytext
Address=address
street
house
City=city

What is problem with my code?


回答1:


I strongly recommend you read up on your problems on Michael Kaplan's blog.

If you absolutely have to use INI files, don't use the deprecated Win32 API functions you are using right now. They are buggy and bugs sure won't get fixed anymore as they are deprecated by now.

Instead use SimpleIni a very decent cross-platform implementation of an INI reader/writer for C++.

Microsoft (as a whole) seems to be unsure whether they prefer registry or other mechanisms for storing configuration data. At some point it was INI files, then it was the registry (to me a superior mechanism) and then it seemed to shift towards XML and other file-based storage mechanisms. It's certainly your use-case that will define what you need, but consider all the words of caution about using these deprecated functions and look at least for an alternative mechanism of working with INI file if you have to.




回答2:


Well seeing that is not the proper format for an INI file for the API functions, what do you expect?

The format for an ini file is:

[section]
item1=item1text
item2=item2text
...

[anothersection]
item1=item1text
item2=item2text
...

If you want to use the ini API calls, then you must adhere to the format. You want city, street, and house to be a part of the City item? Then put them all on the "same line" and use a separator that you can later parse for each field. You could use a comma, pipe, or anything else that won't be part of the text.



来源:https://stackoverflow.com/questions/11451641/writeprivateprofilestring-is-not-adding-property-to-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!