TIniFile->ReadString returns null instead of ""

712 views Asked by At

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

2

There are 2 answers

0
Remy Lebeau On BEST ANSWER

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.

1
IceCold On

My question is stupid but I won't delete it. Let others learn from it too. It was my Delphi brain trying wrap around the weird C++ concepts :)

Delphi-style strings (AnsiString, RawByteString, UnicodeString, and WideString) are not actually NULL in C++Builder, EVEN though this is what the debugger shows. In other words, whenever your debugger shows NULL for such a string, think of it as an "empty string" instead.

To be noted also that

if (s == NULL)

does not return what you expect. Use s.IsEmpty() instead.

Here is the complete answer:

XE6 How do you check if a UnicodeString is null?