c++builderc++builder-10.2-tokyo

TIniFile->ReadString returns null instead of ""


I have this piece of code that refuses to return "DefaultVal" when "CurrentFile" is empty:

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();
         }
}
//---------------------------------------------------------------------------

This is the INI file:

[x]
CurrentFile=

If I edit the INI file to CurrentFile= "something" then the code works and s correctly contains "something".

What am I doing wrong?

C++ Builder Tokyo 10.3.2


Solution

  • TIniFile::ReadString() returns the Default value only if the specified Ident value does not exist at all. If the Ident value exists but is blank, or there is an error reading it, a blank string is returned instead. If you want your Default value to be used if the Ident value is blank, you will have to check for that manually, eg:

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

    Note that TIniFile::ReadInteger() returns the Default value if the Ident value can't be converted to an int for any reason, whether that be because it does not exist, it is blank, it cannot be read, it is not in numerical hexadecimal format, etc.