TIniFile-> ReadString返回null而不是“”

时间:2018-10-01 08:40:17

标签: c++builder c++builder-10.2-tokyo

我有一段代码,当“ CurrentFile”为空时,拒绝返回“ DefaultVal”:

delete

这是INI文件:

void __fastcall TForm1::Button2Click(TObject *Sender)
{
      TIniFile *pIni = new TIniFile("c:\\Test\\MyIni.ini");
      try
         {
         int i = pIni->ReadInteger (L"x", L"Level",  0);  //This is ok

         UnicodeString s = pIni->ReadString ("x", "CurrentFile",  "DefaultVal");   //Debugger shows s = NULL
         }
      __finally
         {
         pIni->Free();
         }
}
//---------------------------------------------------------------------------

如果我将INI文件编辑为[x] CurrentFile= ,则代码可以正常工作并且s正确包含“某物”。

我在做什么错?

C ++ Builder Tokyo 10.3.2

2 个答案:

答案 0 :(得分:1)

TIniFile::ReadString()仅在指定的Default值根本不存在的情况下才返回Ident值。如果Ident值存在但为空,或者读取时出错,则返回空白字符串。如果您希望Default值为空白时使用Ident值,则必须手动检查该值,例如:

String s = pIni->ReadString (_D("x"), _D("CurrentFile"), _D("")); 
if (s.IsEmpty()) // or: if (s == _D(""))
    s = _D("DefaultVal");

请注意,如果出于任何原因 而无法将TIniFile::ReadInteger()值转换为Default,则Ident会返回int值那是因为它不存在,为空白,无法读取,不是数字十六进制格式等。

答案 1 :(得分:0)

我的问题很愚蠢,但我不会删除它。也让其他人从中学习。这是我的Delphi大脑试图绕过奇怪的C ++概念:)

Delphi风格的字符串(AnsiStringRawByteStringUnicodeStringWideString)在C ++ Builder中实际上不是NULL,即使这是调试器也是如此节目。换句话说,只要调试器为这样的字符串显示NULL,就应将其视为“空字符串”。

还要注意

if (s == NULL)

不返回您的期望。请改用s.IsEmpty()

这是完整的答案:

XE6 How do you check if a UnicodeString is null?

相关问题