Read-only archive of the All About Symbian forum (2001–2013) · About this archive

how to convert TBuf to TDesC8

2 replies · 8,877 views · Started 11 April 2003

I am using this code and I am not able to write data into the file.
I have some information in a TBuf that have to be converted into TDesC8, how can i convert TBuf to TDesC8 ?

Though if i am able to print the values of the variable on the screen but not able to write the values of the variable into the file.

***********************************************
_LIT(KFileName,"C:\\Results.txt"😉;

TInt init;
TBuf<128> buffer;
RFile file;
RFs iFs;

init = timer_init();

buffer.Format(_L("Return value of timer_init() is %d"😉, init); //text+int value in the buffer
iInfoMsgWin->StartDisplay(buffer, EHCenterVCenter); // printing on the screen

User::LeaveIfError(iFs.Connect());
file.Create(iFs, KFileName, EFileStreamText|EFileWrite);

file.Write(buffer); // write operation get fails here

*********************************************

Thanks.

Add the following to your code.
[code:1]TBuf8<128> buf8;
buf8.Copy(buffer);
file.Write(buf); [/code:1]

The problem you're experiencing is that you have a unicode (16-bit) descriptor TBuf, and you need to pass this to RFile::Write which takes a 8-bit (essentially binary) descriptor.

If you are sure your TBuf doesn't contain any non-ascii characters then you can use TDes8::Copy() to convert to a binary descriptor. However, if you really have a unicode descriptor this won't work and you'll lose data.

What you could do is do a byte copy of the data like so:

[code:1]
TBuf<64> buf16 = _L("Some text here");
TBuf8<128> buf8;
buf.Copy((TUint8*)buf16.PtrZ());
[/code:1]

Note that this requires that buf16 has a length of < 64, and wastes memory for the copy.

So the best solution is to create a TPtr8 that points to the data in the TDes16 like so:

[code:1]
TBuf16<128> data = _L("Some data you want to save");
TPtrC8 ptr((TUint8*)data.Ptr(), data.Size());

fs.Write(ptr);
[/code:1]