I'm using the community version of C++ builder (10.3) under Windows 10 to develop an app to run on a Samsung Galaxy A40.
One thing I can't seem to get working is saving the contents of TListBox to a file.
Being a newbie to Android, I'm not sure about where this file should appear and what rights I need.
I've tried the following in a function to save the contents of a listbox to a file, but can't seem to open a file to write to. It always returns -1 :
int hFile; // File Handle
int ByteCt=0;
hFile = FileOpen("Shopping.lst", fmOpenWrite);
if (hFile > 0)
{
for (int i=0; i<ListBox1->Count; i++)
{
ByteCt+=FileWrite(hFile,ListBox1->Items[i].Text.c_str(),
ListBox1->Items->Strings[i].Length());
ByteCt+=FileWrite(hFile,"\n\r",2);
}
FileClose(hFile);
}
Is there something basic I've missed, or what ?
Use the
System::Ioutils::TPathclass to determine various system paths that your app can access. See Standard RTL Path Functions across the Supported Target Platforms for details. For example:But FYI,
ListBox1->Itemsis aTStrings, which has its ownSaveToFile()method, eg:You are just duplicating what
SaveToFile()already does for you. So you don't need to write the strings manually - especially since you are not even writing them correctly to begin with!Stringin C++Builder is an alias forUnicodeString, which is a UTF-16 encoded string. ItsLength()specifies the number ofWideChar(char16_ton Android) elements it contains, butFileWrite()deals in raw bytes only. So you are writing only 1/2 of the bytes of eachStringsincesizeof(WideChar)=2. And also,"\n\r"is not a valid line break to use, either. You would need to use"\r\n"or just"\n", or use the RTL'ssLineBreakglobal constant. But worse, you are trying to write theStrings in their original UTF-16 format but are writing the line breaks in an 8bit ANSI/UTF-8 format. So you end up with a mixed-encoding file, which many softwares won't be able to read correctly.If you really want to write the
Strings manually then it needs to look more like this instead:However, rather than using
FileWrite()directly, consider usingTStreamWriterinstead, eg: