Question

I am using Embarcadero C++Builder XE and I am trying to write 123456 to a textfile like this:

String teststring = "123456";
int iFileHandle = FileCreate("example.txt");
int iLength = teststring.Length()*sizeof(wchar_t);
int output = FileWrite(iFileHandle, teststring.w_str(), iLength);

But the output is this:

1 2 3 4 5 6

Spaces have been added after every character. I can see that iLength is 12 so are the spaces added when the string is created and how can I prevent this?

Was it helpful?

Solution

You could just uses a string list and add the string you want to then then save the string list to file.

TStringList *Temp = new TStringList( );
Temp->Add("123456");
Temp->SaveToFile(("example.txt");

delete Temp;

OTHER TIPS

System::String is encoded in XE as UTF-16, which uses 16-bit values. Those "spaces" you see are the high-order bytes of those character values, which are nulls for ASCII character values. If you don't want those bytes in your file, then you have to convert the String to a different encoding that doesn't use them, eg:

String teststring = "123456"; 
AnsiString s = teststring; // or UTF8String, or any other MBCS encoding you want
int iFileHandle = FileCreate("example.txt"); 
int iLength = s.Length() * sizeof(AnsiChar); 
int output = FileWrite(iFileHandle, s.c_str(), iLength); 

iLength is supposed to be 12 since string length is 6 and size of wchar_t is 2 in this case. So, indeed, spaces are not added when the string is created. These are 2., 4., 6., 8. and 10. bytes allocated and initialized to space character when you create a wide string from a string here:

teststring.w_str()

Try using c_str() instead:

String teststring = "123456";
int iFileHandle = FileCreate("example.txt");
int iLength = teststring.Length();
int output = FileWrite(iFileHandle, teststring.c_str(), iLength);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top