WritePrivateProfileSection写入额外的caracs

时间:2017-11-15 21:45:45

标签: c++ winapi

我有一个让我发疯的问题。 我有std :: string包含一些数据,我想保存在INI文件中。

所以我做了如下:

std::string strBuffer;
char line[MAX_BUFFER + 1];

for (int i=0; i < NbrElts; i++)
{
    //Here I get pData filled with data 

    sprintf_s(line, "%s%d=%s,%s,%s,%s,%s,%s,%s", "key", i, pData->sType, pData->sId, pData->sName, pData->sCountry, pData->sSite, pData->sCDB, pData->sShortName);
    strBuffer += line;
}

WritePrivateProfileSection("PERSONAL", strBuffer.c_str(), GetMYFile());

所以在这一点上,当我使用调试器时,我的strBuffer的内容是好的,但是当执行WritePrivateProfileSection时,我有额外的caracters写入我的文件。

我尝试在写入INI文件之前使用转换但没有成功。 任何帮助可能是什么线索?

谢谢。

示例:

strBuffer包含"HELLO WORLD",在我的文件中,我得到HELLO WORLD נננ

  

PS:除了我错过了在每个键之后添加“\ 0”,主要问题来自于使用std :: string,因为它不处理null   终止,所以即使加上“\ 0”,我仍然得到了凌乱的输出   ---&GT;必须改为char []。

1 个答案:

答案 0 :(得分:0)

string.c_str()已经以空值终止,我们将其表示为

{ 'H', 'i', '\0' };

WritePrivateProfileSection需要多个字符串,由单个'\0'分隔,以'\0\0'结尾,例如对于两个条目x=1y=2

{ 'x', '=', '1', '\0', 'y', '=', '2', '\0', '\0' }

您的代码存在问题

s += line;

期望rhs上有一个以零结尾的字符串。你可以使用:

int len = sprintf(buffer, "%s=%d\0", key, value); // TODO! Check for error!
s += std::string(line, len); // don't stop at the first '\0'!

但此时我会使用std::vector<char>代替,因为std :: string行为在这里似乎太容易出错,而且我们依赖于构成字符串的更精细的细节。