代码之家  ›  专栏  ›  技术社区  ›  IceCold

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

  •  1
  • IceCold  · 技术社区  · 7 年前

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

    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=
    

    如果我将INI文件编辑为 CurrentFile= "something"

    我做错什么了?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Remy Lebeau    7 年前

    TIniFile::ReadString() 返回 Default 仅当指定 Ident 值根本不存在。如果 值存在但为空,或者读取时出错,将返回一个空字符串。如果你想 如果 识别号

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

    请注意 TIniFile::ReadInteger() 违约 如果 识别号 int 对于 任何

        2
  •  0
  •   Remy Lebeau    7 年前

    我的问题很愚蠢,但我不会删掉它。让别人也从中学习。这是我的德尔菲大脑试图绕过奇怪的C++概念:

    Delphi样式字符串( AnsiString RawByteString UnicodeString ,和 WideString )在C++Builder中实际上不是NULL,即使调试器显示了这一点。换句话说,每当调试器显示 NULL 对于这样的字符串,请将其视为“空字符串”。

    还需要指出的是

    if (s == NULL)
    

    不会返回您所期望的。使用 s.IsEmpty()

    以下是完整答案:

    XE6 How do you check if a UnicodeString is null?