Symbian
Symbian Developer Library

SYMBIAN OS V9.4

Feedback

[Index] [Previous] [Next]


Descriptors example code

[Top]


BinaryData: handling general binary data with descriptors


Example code

Found in: examples\Base\BufsAndStrings\Desc\BinaryData

The files reproduced here are the main files contained in the examples directory. Some extra files may be needed to run the examples, and these will be found in the appropriate examples directory.

// BinaryData.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate how descriptors can handle 
// general binary data.

#include "CommonFramework.h"

//
// Common literal text
//
_LIT(KTxtNewLine,"\n");

//
// Common format strings
//
_LIT(KCommonFormat2,"Size()=%d; MaxLength()=%d\n");
_LIT(KCommonFormat3,"0x%02x ");
_LIT(KCommonFormat4,"; Length()=%d;\n");

// do the example
LOCAL_C void doExampleL()
    {
    TInt counter;
    TInt index;
    
                // For general binary data, construct an 8 bit
                // variant descriptor. Binary data is always
                // treated as 8 bit data regardless of the 
                // build.
                //
                // This example constructs a TBuf8 using the 
                // default constructor.                    

    TBuf8<32> buffer;

                // Look at:
                //   1. Descriptor content
                //   2. Length of descriptor
                //   3. Size of descriptor
                //   4. Maximum length of descriptor
                //  
                // Length is zero. Maximum length is 32.
                // Size is zero.  
    _LIT(KFormat1,"\"%S\"; Length()=%d; ");
    console->Printf(KFormat1,&buffer,buffer.Length());
    console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength());
                
                // Set up an area in memory initialised
                // with binary data.
    TUint8 data[6] = {0x00,0x01,0x02,0xAD,0xAE,0xAF};
                
                // Put data into descriptor
    buffer.Append(&data[0],sizeof(data));

                // Append the following byte values
    buffer.Append(0xFD);
    buffer.Append(0xFE);
    buffer.Append(0xFF);

                // Length is now 9; maxlength is still 32;
                // Size is always 9 regardless of build.
    counter = buffer.Length();
    console->Printf(KTxtNewLine);
    for (index = 0; index < counter; index++)
        console->Printf(KCommonFormat3,buffer[index]);

    console->Printf(KCommonFormat4,buffer.Length()
                      );
    console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength());                              
                // We can also mix text characters and
                // general binary data.
    buffer.Append('A');
    buffer.Append('B');
    buffer.Append(0x11);                          
    
                // Show it
    counter = buffer.Length();
    console->Printf(KTxtNewLine);
    for (index = 0; index < counter; index++)
        console->Printf(KCommonFormat3,buffer[index]);
    
    console->Printf(KCommonFormat4,buffer.Length());
    console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength());                              
    }
// BinaryData.mmp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// using relative paths for sourcepath and user includes

// No explicit capabilities required to run this.

TARGET        BinaryData.exe
TARGETTYPE    exe
UID           0
VENDORID 0x70000001

SOURCEPATH    .
SOURCE        BinaryData.cpp

USERINCLUDE   .
USERINCLUDE   ..\..\..\CommonFramework
SYSTEMINCLUDE \Epoc32\include

LIBRARY       euser.lib

CAPABILITY    None
// BLD.INF
// Component description file
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

PRJ_MMPFILES

BinaryData.mmp

Description

The example shows how descriptors can handle general binary data by explicitly using the 8 bit descriptor class variants TBufC8<TInt>, TBuf8<TInt>, TPtr8 etc.

Contrast this with examples where descriptors contain text. These examples almost always use the non-explicit forms TBufC<TInt>, TBuf<TInt>, TPtr etc; these are typedef'd to the 16 bit variant.


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


Buffer: basic idea of buffer descriptors


Example code

Found in: examples\Base\BufsAndStrings\Desc\Buffer

// Buffer.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate the basic ideas of
// buffer descriptors.

#include "CommonFramework.h"

//
// Common literal text
//
_LIT(KTxtHelloWorld,"Hello World!");
_LIT(KTxtRepText,"Replacement text");
_LIT(KTxtTBufC,"TBufC: ");
_LIT(KTxtTPtr,"TPtr:  ");

//
// Common Format strings
//
_LIT(KCommonFormat2,"\"%S\"; ");
_LIT(KCommonFormat3,"Descriptor at %x; Ptr()=%x; ");
_LIT(KCommonFormat6,"\"%S\"; Ptr()=%x; Length()=%d; Size()=%d\n");
_LIT(KCommonFormat7,"\"%S\"; Ptr()=%x; Length()=%d; Size()=%d; ");
_LIT(KCommonFormat8,"\nMaxLength()=%d\n");
_LIT(KCommonFormat9,"Length()=%d; Size()=%d;\n");
_LIT(KCommonFormat10,"MaxLength()=%d\n");


LOCAL_C void doExampleL()
    {                  
                // Set up an area and initialise to a 
                // C style string (including the NULL).
    TText cstr[13] =  {'H', 'e' ,'l' ,'l' ,'o', ' ',
                       'W', 'o','r', 'l', 'd', '!', '\0'};

                // Construct a TBufC using the NULL 
                // terminated string in cstr to initialise
                // it.
    TBufC<16> bufc1(&cstr[0]);

                // Look at the address of the C string
    _LIT(KFormat1,"C string at %x; \n");
    console->Printf(KFormat1,&cstr[0]);
                                                      
                // Look at: 
                //   1. Descriptor content
                //   2. Address of descriptor
                //   3. Address of descriptor data area
                //   4. Length of descriptor
                //   5. Size of descriptor
                //         
                // Address of descriptor data area is 
                // different from the address of cstr but
                // is offset 4 from the start of the 
                // descriptor itself.
                //
                // Descriptor length is 12.
                //
                // The template parameter value defines 
                // the length of the descriptor data area 
                // and, therefore, governs its size 
                // (depending on the build variant).
                // Size of data is 24
    console->Printf(KCommonFormat2,&bufc1);
    console->Printf(KCommonFormat3,&bufc1,bufc1.Ptr());
    _LIT(KFormat4,"Length()=%d; Size()=%d\n");
    console->Printf(KFormat4,bufc1.Length(),bufc1.Size());   
                                              
                // If the TBufC is to hold string data on
                // construction, use a _LIT macro.
    TBufC<16> bufc2(KTxtHelloWorld);

                // Cannot modify existing data but can replace
                // it entirely using assignment operator. 
                // The replacement text must not have a length 
                // greater than 16
    bufc2 = KTxtRepText;
    _LIT(KFormat5,"\"%S\"; Length()=%d; Size()=%d\n");
    console->Printf(KFormat5,&bufc2,bufc2.Length(),bufc2.Size());

                // Replacing text which has a length > 16
                // causes panic !!
                // 
                // Remove the "//" marks on the next two lines
                // to see this happen
    //_LIT(KTxtRepTextPanic,"Text replacement causes panic");
    //bufc2 = KTxtRepTextPanic;
    
    
                // The Des() function returns a TPtr to the
                // TBufC.
                // The TBufC data can be changed through 
                // the TPtr.
                // The maximum length of the TPtr is the 
                // value of the TBufC template parameter,
                // i.e. 16 

    bufc2 = KTxtHelloWorld;
    TPtr ptr = bufc2.Des();
    
    console->Printf(KTxtTBufC);
    console->Printf(KCommonFormat6,
                    &bufc2,
                    bufc2.Ptr(),
                    bufc2.Length(),
                    bufc2.Size()
                   );
    
    console->Printf(KTxtTPtr);
    console->Printf(KCommonFormat7,
                    &ptr,
                    ptr.Ptr(),
                    ptr.Length(),
                    ptr.Size()
                   );

    console->Printf(KCommonFormat8,ptr.MaxLength());

                // Now change the TBufC data through
                // the TPtr. This is OK provided the length
                // of the changed data does not exceed 16.
                //
                // The following change deletes the last 
                // character (the "!") and appends 
                // the characters " & Hi".
                //
                // Note that the length of both the TBufC 
                // and the TPtr reflect the changed data.
    _LIT(KTxtAndHi," & Hi");
    ptr.Delete((ptr.Length()-1),1);
    ptr.Append(KTxtAndHi);

    console->Printf(KTxtTBufC);
    console->Printf(KCommonFormat6,
                    &bufc2,
                    bufc2.Ptr(),
                    bufc2.Length(),
                    bufc2.Size()
                   );

    console->Printf(KTxtTPtr);
    console->Printf(KCommonFormat7,
                    &ptr,
                    ptr.Ptr(),
                    ptr.Length(),
                    ptr.Size()
                   );
    console->Printf(KCommonFormat8,ptr.MaxLength());

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    
    _LIT(KTxtBasicConcepts,"\n-->TBuf basic concepts");
    console->Printf(KTxtBasicConcepts);
    _LIT(KTxtPressToContinue," (press any key to continue)\n");
    console->Printf(KTxtPressToContinue);
    console->Getch();

                // Construct a TBuf using a Literal              
    TBuf<16> buf(KTxtHelloWorld);
    
                // Look at: 
                //   1. Descriptor content
                //   2. Address of descriptor
                //   3. Address of descriptor data area
                //   4. Length of descriptor
                //   5. Size of descriptor
                //   6. Maximum length of descriptor      
                //
                // Like a TBufC, the address of the descriptor
                // data area is offset 4 from the start of the
                // descriptor itself.
                //
                // Descriptor length is 12.
                //
                // The template parameter value defines 
                // the maximum length of the descriptor. 
                // and, therefore, governs its size 
                // (depending on the build variant).
                // Size of data is 24
                                
    console->Printf(KCommonFormat2,&buf);
    console->Printf(KCommonFormat3,&buf,buf.Ptr());
    console->Printf(KCommonFormat9,buf.Length(),buf.Size()); 
    console->Printf(KCommonFormat10,buf.MaxLength());
                          
                // The data can be modified
    buf.Append('@');
    console->Printf(KCommonFormat2,&buf);
    console->Printf(KCommonFormat9,buf.Length(),buf.Size()); 
    console->Printf(KCommonFormat10,buf.MaxLength());

                 // Length can be changed; data represented
                 // by the descriptor is now "Hel"
    buf.SetLength(3);
    console->Printf(KCommonFormat2,&buf);
    console->Printf(KCommonFormat9,buf.Length(),buf.Size()); 
    console->Printf(KCommonFormat10,buf.MaxLength());

                // Length can be zeroised; no data is now 
                // represented by the descriptor but 
                // the maximum length is still 16
    buf.Zero();
    console->Printf(KCommonFormat2,&buf);
    console->Printf(KCommonFormat9,buf.Length(),buf.Size()); 
    console->Printf(KCommonFormat10,buf.MaxLength());
                                                          
                // The data can be replaced entirely 
                // using the assignment operator.
                // The replacement text must not have a
                // length greater than 16.
    buf = KTxtRepText;
    console->Printf(KCommonFormat2,&buf);
    console->Printf(KCommonFormat9,buf.Length(),buf.Size()); 
    console->Printf(KCommonFormat10,buf.MaxLength());
    
                // Replacing text which has a length > 16
                // causes panic !!
                // 
                // Remove the "//" marks on the next two lines
                // to see this happen
    //_LIT(KTxtRepTextPanic,"Text replacement causes panic");
    //buf = _L("Text replacement causes panic!");
    }

Description

This example shows the basic idea of buffer descriptors and how they are used.


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


InFunct: using descriptors in function interfaces

Found in: examples\Base\BufsAndStrings\Desc\InFunct

// InFunct.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate the usage of descriptors in function interfaces.

#include "CommonFramework.h"

//
// Literal text
//

_LIT(KDataTPtrC,"A TPtrC descriptor");
_LIT(KDataTPtr,"A TPtr descriptor");
_LIT(KDataTBufC,"A TBufC descriptor");
_LIT(KDataTBuf,"A TBuf descriptor");
_LIT(KDataHBufC,"An HBufC descriptor");

//
// Common format strings
//

_LIT(KCommonFormat2,"0x%02x ");

// A set of functions called by the example code
LOCAL_C void StringRead(const TDesC& aString); 
LOCAL_C void StringWrite(TDes& aString);       
LOCAL_C void BufferRead(const TDesC8& aBuffer); 
LOCAL_C void BufferWrite(TDes8& aBuffer);       
         
// Do the example
LOCAL_C void doExampleL()
    {                  
                // We create four functions:
                // StringRead()
                // StringWrite()
                // BufferRead()
                // BufferWrite() 
                // to illustrate the use of descriptors
                // in function interfaces    
    
    TText      area[48]; 
    TPtrC      ptrc;
    TPtr       ptr(&area[0],48);

    TBufC<48>  bufc;
    TBuf<48>   buf;
    HBufC*     hbufcptr;

    hbufcptr = HBufC::NewL(48);

                // Set up some data for our
                // descriptors
    ptrc.Set(KDataTPtrC);    // "A TPtrC descriptor"        
    ptr       = KDataTPtr;   // "A TPtr descriptor"
    bufc      = KDataTBufC;  // "A TBufC descriptor"
    buf       = KDataTBuf;   // "A TBuf descriptor"
    *hbufcptr = KDataHBufC;  // "An HBufC descriptor"

                // We can pass a reference to all
                // descriptor types to StringRead() but    the 
                // function cannot change the 
                // descriptor content 
    StringRead(ptrc);                    // <-- a TPtrC
    StringRead(ptr);                     //    <-- a TPtr
    StringRead(bufc);                    // <-- a TBufC
    StringRead(buf);                     //    <-- a TBuf
    StringRead(*hbufcptr);               //  <-- an HBufC
                   
                // We can only pass a reference to those
                // descriptors which are derived 
                // from TDes, to StringWrite();
                // these are the modifiable
                // descriptors: TPtr and TBuf. 
                //
                // The compiler will not permit a reference
                // to any other descriptor type to 
                // be passed. 
  //StringWrite(ptrc);                   <-- Illegal
    StringWrite(ptr);                    // <-- a TPtr
  //StringWrite(bufc);                     <-- Illegal
    StringWrite(buf);                    // <-- a TBuf
  //StringWrite(*hbufcptr);                <-- Illegal

    delete hbufcptr;
    
    _LIT(KTxtPressToContinue," (press any key to continue)\n");
    console->Printf(KTxtPressToContinue);
    console->Getch();
                
    TUint8      data1[3] = {0x00,0x01,0x02};
    TUint8      data2[3] = {0x03,0x04,0x05};
    TUint8      data3[3] = {0x06,0x07,0x08};
    TUint8      data4[3] = {0x09,0x0A,0x0B};
    TUint8      data5[3] = {0x0C,0x0D,0x0E};
                             
                // Use the 8 bit variants explicitly for
                // general binary data.

                // ptrc8's data area is data1[]
                // ptr8's data areais data2[]
    TPtrC8      ptrc8(&data1[0],3);
    TPtr8       ptr8(&data2[0],3,3);

                // bufc8 contains a copy of data3[] data
                // buf8 contains a copy of data4[] data
                // hbufcptr8 contains a copy of data5[] data
    TBufC8<3>  bufc8= TPtrC8(&data3[0],3);
    TBuf8<3>   buf8= TPtrC8(&data4[0],3);
    HBufC8*    hbufcptr8;

    hbufcptr8  = HBufC8::NewL(3);
    *hbufcptr8 = TPtrC8(&data5[0],3);

                // We can pass a reference to all
                // descriptor types to BufferRead()
                // but the function cannot change the 
                // descriptor content 
    BufferRead(ptrc8);                   // <-- a TPtrC
    BufferRead(ptr8);                    // <-- a TPtr
    BufferRead(bufc8);                   //  <-- a TBufC
    BufferRead(buf8);                    // <-- a TBuf
    BufferRead(*hbufcptr8);              //   <-- an HBufC
    
                // We can only pass a reference to those
                // descriptors which are derived 
                // from TDes, to BufferWrite; these are 
                // the modifiable descriptors: TPtr and TBuf. 
                //
                // The compiler will not permit a reference
                // to any other descriptor type to 
                // be passed. 
  //BufferWrite(ptrc8);                  <-- Illegal
    BufferWrite(ptr8);                   //  <-- a TPtr
  //BufferWrite(bufc8);                    <-- Illegal
    BufferWrite(buf8);                   //  <-- a TBuf
  //BufferWrite(*hbufcptr8);            <-- Illegal               

      delete hbufcptr8;
    }



// ************************************************
// Functions used by doInterface()
// ************************************************
LOCAL_C void StringRead(const TDesC& aString)
    {
                // A function which handles the content
                // of ANY descriptor passed to it but CANNOT
                // change that descriptor.
                //
                // Function displays descriptor content,
                // length and size.
                //
                // All descriptors can be passed to this 
                // function    because all descriptors are 
                // ultimately derived from TDesC.
                //
                // Note, however, that all data members and
                // function members in the TDes abstract class
                // cannot be accessed (recall that TDes is 
                // derived from TDesC).
                // These include the data member containing 
                // the maximum length and all modifying 
                // member functions.
    
    _LIT(KFormat5,"\"%S\"; %d; %d\n");
    console->Printf(KFormat5,&aString,aString.Length(),aString.Size());
    }


LOCAL_C void StringWrite(TDes& aString)
    {
                // A function which handles the content
                // of a descriptor derived from TDes;
                // i.e. the modifiable descriptors TPtr and
                // TBuf. 
                //
                // Function changes the content of the
                // referenced descriptors and then displays
                // their content, length, size and maximum
                // length.
                //
                // Note that the references to TPtrC, TBufC
                // and HBufC cannot be passed.  
    _LIT(KTxtModStringWrite," modified by StringWrite");           
    aString.Append(KTxtModStringWrite);
    _LIT(KFormat3,"\"%S\"; %d; %d; %d\n");
    console->Printf(KFormat3,
                    &aString,
                    aString.Length(),
                    aString.Size(),
                    aString.MaxLength()
                   );
    }


LOCAL_C void BufferRead(const TDesC8& aBuffer)
    {
                // A function which handles the content
                // of ANY descriptor passed to it but
                // CANNOT change that descriptor.
                //
                // Function displays descriptor content,
                // length and size.
                //
                // All descriptors can be passed to this 
                // function because all descriptors are 
                // ultimately derived from TDesC.
                //
                // Note, however, that all data members 
                // and function members in the TDes abstract
                // class cannot be accessed (recall that 
                // TDes is derived from TDesC).
                // These include the data member containing
                // the maximum length and all modifying
                // member functions.
    for (TInt ix = 0; ix < aBuffer.Length(); ix++)
        console->Printf(KCommonFormat2,aBuffer[ix]);
    
    _LIT(KFormat4,"; %d; %d\n");
    console->Printf(KFormat4,aBuffer.Length(),aBuffer.Size());   
    }


LOCAL_C void BufferWrite(TDes8& aBuffer)
    {
                // A function which handles the content
                // of a descriptor derived from TDes;
                // i.e. the modifiable descriptors TPtr
                // and TBuf
                //
                // Function changes the content of the 
                // referenced descriptors and then displays
                // their content, length, size and maximum
                // length.
                //
                // Note that the references to TPtrC, TBufC
                // and HBufC cannot be passed.

    _LIT(KTxtModBufferWrite,"Modified by BufferWrite ");           
    console->Printf(KTxtModBufferWrite);
                
    for (TInt ix = 0; ix < aBuffer.Length(); ix++)
        {
        aBuffer[ix] += 0xF0;
        console->Printf(KCommonFormat2,aBuffer[ix]);
        }

    _LIT(KFormat1,"; %d; %d; %d\n");
    console->Printf(KFormat1,
                    aBuffer.Length(),
                    aBuffer.Size(),
                    aBuffer.MaxLength()
                   );
    }

Description

This example shows how descriptors can be used in function interfaces. Specifically, it shows the use of:

as function arguments.


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


HeapBuffer: heap buffer descriptors

Found in: examples\Base\BufsAndStrings\Desc\HeapBuffer

// HeapBuffer.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate the basic ideas of heap buffer descriptors.

#include "CommonFramework.h"

//
// Common literal text
//
_LIT(KTxtHelloWorld,"Hello World!");
_LIT(KTxtHelloWorldMorning,"Hello World! Morning");
_LIT(KTxtAndHi," & Hi");

//
// Common Format strings
//
_LIT(KCommonFormat1,"Size()=%d;\nMaxLength()=%d\n");
_LIT(KCommonFormat2,"Ptr()=%x; Length()=%d; ");
_LIT(KCommonFormat5,"Ptr()=%x; Length()=%d; Size()=%d\n");


// Do the example
LOCAL_C void doExampleL()
    {
    
                // An HBufC is always constructed on the heap
                // using the static New(), NewL() or NewLC()
    HBufC* buf;

                // Construct an HBufC.
                // This descriptor can hold up to 15 data 
                // items.
                // The current length is zero
    buf  = HBufC::NewL(15);
    CleanupStack::PushL(buf);

                // Note, we could replace the above two lines of code
                // with the single line: buf  = HBufC::NewLC(15);


                // Show 1. Content
                //      2. address of descriptor
                //      3. address of descriptor data area
                //      4. length of descriptor
                //      5. size of descriptor
                // The address of the descriptor data area
                // is offset 4 from the start of the 
                // descriptor itself.
    _LIT(KFormat10,"\"%S\"; descriptor at %x; ");
    console->Printf(KFormat10,buf,buf);
    console->Printf(KCommonFormat5,buf->Ptr(),buf->Length(),buf->Size());
                           
                // Set up some data into the HBufC 
    *buf = KTxtHelloWorld;          // "Hello World!"

                // Show 1. Content
                //      2. length of descriptor
                //      3. size of descriptor
    _LIT(KFormat9,"\"%S\"; ");
    console->Printf(KFormat9,buf);
    _LIT(KFormat8,"Length()=%d; Size()=%d\n");
    console->Printf(KFormat8,buf->Length(),buf->Size());

                // Now want to replace the text with:
                // "Hello World! Morning"
                // Resulting length would be > 15
                // So, reallocate the HBufc first
                // to make it bigger

    buf = buf->ReAllocL(20);

               // Assign the new text.
    *buf = KTxtHelloWorldMorning;   // "Hello World! Morning"

               // Show it
    _LIT(KFormat7,"\n\"%S\"; \n(1st realloc') desc'at %x; ");
    console->Printf(KFormat7,buf,buf);
    console->Printf(KCommonFormat5,buf->Ptr(),buf->Length(),buf->Size());           

                // buf may point to the same area as before.
                // In general, this is not the case so DO 
                // NOT ASSUME. 
    
    buf = buf->ReAllocL(22);
    _LIT(KFormat6,"\n\"%S\"; \n(2nd realloc') desc'at %x; ");
    console->Printf(KFormat6,buf,buf);
    console->Printf(KCommonFormat5,buf->Ptr(),buf->Length(),buf->Size());
    
                // The Des() function returns a TPtr to the
                // HBufC.
                // The HBufC data can be changed through 
                // the TPtr.
                // The maximum length of the TPtr is 
                // determined from the size of the cell 
                // allocated to the data area of the HBufC.
                // In this example, the value has been rounded 
                // up to 24.
    TPtr ptr = buf->Des();

    _LIT(KFormat11,"TPtr descriptor at %x; ");
    console->Printf(KFormat11,&ptr);
    console->Printf(KCommonFormat2,ptr.Ptr(),ptr.Length());
    console->Printf(KCommonFormat1,ptr.Size(),ptr.MaxLength());

                // Now change the HBufC data through
                // the TPtr. This is OK provided the length
                // of the changed data does not exceed the 
                // maximum length.
                //
                // The following change deletes the last 
                // nine characters and then appends 
                // the characters " & Hi".
                //
                // Note that the length of both the HBufC 
                // and the TPtr reflect the changed data.
    
    ptr.Delete((ptr.Length()-9),9);
    ptr.Append(KTxtAndHi); // " & Hi"
    
                // Look at it from HBufC's viewpoint
    _LIT(KFormat4,"\n\"%S\";\nHBufC descriptor at %x; ");
    console->Printf(KFormat4,buf,buf);

    console->Printf(KCommonFormat5,buf->Ptr(),buf->Length(),buf->Size());

                // Look at it from TPtr's viewpoint
    _LIT(KFormat3,"\"%S\"; \nTPtr  descriptor at %x; ");
    console->Printf(KFormat3,&ptr,&ptr);
    console->Printf(KCommonFormat2,ptr.Ptr(),ptr.Length());
    console->Printf(KCommonFormat1,ptr.Size(),ptr.MaxLength());
                // Pop the HBufC off the cleanup stack
                // and destroy it (i.e. the HBufC)
    CleanupStack::PopAndDestroy();
    }


    
    

Description

The example shows use of the HBufC heap buffer descriptor and:


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


Modifier: modifiable descriptors


Example code

Found in: examples\Base\BufsAndStrings\Desc\Modifier

// Modifier.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate some of the modifying member
// functions of descriptors.

#include "CommonFramework.h"

//
// Common literal text 
//
_LIT(KPressAnyKeyToContinue," (press any key to continue)\n");
_LIT(KTextHelloWorld,"Hello World!");
_LIT(KTextHello,"Hello");
_LIT(KTextXYZ,"XYZ");
_LIT(KTextDinner,"D\214ner \205 la Fran\207ais");

//
// Common format strings
//

_LIT(KFormatfourex,"%4x");
_LIT(KFormatBufLenSizeMax,"\"%S\"; %d; %d; %d\n");
_LIT(KFormatLenSizeMax,"; %d; %d; %d\n");
_LIT(KFormatBufLen,"\"%S\"; Length()=%d; ");
_LIT(KFormatSizeMax,"Size()=%d; MaxLength()=%d\n");
_LIT(KFormatCommon,"0x%02x ");

            // Define and implement
            // the overflow handler used
            // by the AppendFormat() example.

class TestOverflow : public TDesOverflow
    {
    void Overflow(TDes& aDes);
    };


void TestOverflow::Overflow(TDes& aDes)
    {
    _LIT(KTextDescOverflow,"Descriptor overflow - maxlength %d\n");
    console->Printf(KTextDescOverflow,aDes.MaxLength());
    }


// Do the example
LOCAL_C void doExampleL()
    {                  

    TInt index;
    TInt counter;

                // Use a TBuf to demonstrate some of these
    TBuf<32> buf(KTextHelloWorld);
        
            //              
            // Copy(),CopyF(), CopyUC() & CopyCP()  * * * 
            //
            // Note that CopyF() CopyUC() & CopyCP() are locale dependent

    _LIT(KTitleCopy,"\n--->Copy(),CopyF(),CopyUC() & CopyCP()\n");
    _LIT(KNoteAboutLocale1,"\nNote that the behaviour of CopyF(), CopyUC() & CopyCP() is\n");
    _LIT(KNoteAboutLocale2,"dependent on the locale.\n");
    console->Printf(KTitleCopy);
    console->Printf(KNoteAboutLocale1);
    console->Printf(KNoteAboutLocale2);
                        
                // Show buf's content,length,size and
                // maximum size.
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());

               // Copy normal
    buf.Copy(KTextDinner);

                // Show buf's content,length,size and 
                // maximum size.
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());
    

                // Copy folded - accents are not preserved
                //
                // (NB the display may use a different code
                // page to that used by the base, in which 
                // case the accents will seem to be preserved)
    buf.CopyF(KTextDinner);
                
                // Show buf's new content,length,size
                // and max size
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());
                // Copy uppercase
                // Note that accents are preserved.
    buf.CopyUC(KTextDinner);
                
                // Show buf's new content,length,size
                // and maximum size
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());

                // Copy capitalised
                // Note that accents are preserved.
    _LIT(KTextCatOnMat,"tHe CaT sAt On ThE mAt - voil\205");
    buf.CopyCP(KTextCatOnMat);
                
                // Show buf's new content,length,size
                // and max size
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());
                          
                // Length of copied text > 32 causes panic !!
                // 
                // Remove the "//" marks on the next two lines
                // to see this happen
    //_LIT(KTxtCausePanic1,"Panic caused by an attempt to replace text.");
    //buf.Copy(KTxtCausePanic1);
    
            //
           // Append() & operator+=  * * * * * * * * * 
            //
    _LIT(KTitleAppend,"\n--->Append & Operator+=");
    console->Printf(KTitleAppend);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // Show buf's content,length,size and
                // maximum size.
    buf = KTextHelloWorld;
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());

                // Append:
                //     1. a single character
                //     2. a descriptor
                //     3. another descrptor using operator +=
                //
                // Generates the string
                // "Hello World!@XYZ##" in buf
    buf.Append('@');
    buf.Append(KTextXYZ);
    _LIT(KTextHashHash,"##");
    buf += KTextHashHash;
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());

            //              
            // Swap()  * * * * * * * * * * * * * * * 
            //
    _LIT(KTitleSwap,"\n--->Swap()");
    console->Printf(KTitleSwap);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();
    
    _LIT(KWhatANiceDay,"What a nice day");
    TBuf<16> altbuf1(KWhatANiceDay);
    buf = KTextHelloWorld;

                // Show buf and altbuf BEFORE swap
    _LIT(KTextBefore,"          BEFORE...\n");
    console->Printf(KTextBefore);
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());
    
    console->Printf(KFormatBufLen,&altbuf1,altbuf1.Length());
    console->Printf(KFormatSizeMax,altbuf1.Size(),altbuf1.MaxLength());
    
                // now swap the descriptors and look at
                // buf and altbuf again;
                // The content, length and size of the 
                // descriptors have swapped; their maximum 
                // lengths have NOT changed.
    buf.Swap(altbuf1);

    _LIT(KTextAfter,"          AFTER...\n");
    console->Printf(KTextAfter);
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());
    
    console->Printf(KFormatBufLen,&altbuf1,altbuf1.Length());
    console->Printf(KFormatSizeMax,altbuf1.Size(),altbuf1.MaxLength()
                      );

                // Swap is ok provided the maximum length
                // of each descriptor is big enough to 
                // hold the other's data.
    
                // altbuf2 is too small to accommodate 
                // buf's data !!
                // 
                // Remove the "//" marks on the next three lines
                // to see this panic
    //_LIT(KTxtxxx,"xxx");
    //TBuf<8>  altbuf2(KTxtxxx);
    //buf = KTextHelloWorld;
    //buf.Swap(altbuf2);
    
    
            //              
            // Repeat()  * * * * * * * * * * * * * * * 
            //
    _LIT(KTitleRepeat,"\n--->Repeat()");
    console->Printf(KTitleRepeat);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // Set current length of buf to 16 and
                // copy repeat the characters "Hello".
                // The descriptor is filled up to 
                // its CURRENT LENGTH.
                // Result is the 16 charcters
                // "HelloHelloHelloH"
                //
                // Note the truncation. 
    buf.SetLength(16);
    buf.Repeat(KTextHello);

                // Look at it.
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());

                // Now set the length to 8 characters
                // and do Repeat again.
                // Result is the 8 characters
                // "HelloHel"

    buf.SetLength(8);
    buf.Repeat(KTextHello);

                // Look at it
    console->Printf(KFormatBufLen,&buf,buf.Length());
    console->Printf(KFormatSizeMax,buf.Size(),buf.MaxLength());
    
           //                
            // Insert() & Delete()  * * * * * * * * *
            //
    _LIT(KTitleInsert,"\n--->Insert() & Delete()");
    console->Printf(KTitleInsert);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // set buf to contain the text "abc" and 
                // look at it
    _LIT(KTextAbc,"abc");
    buf = KTextAbc;
    console->Printf(KFormatBufLenSizeMax,
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // Insert the descriptor at the beginning
                // of buf to give "XYZabc"
                //
    
    buf.Insert(0,KTextXYZ);

                // Look at it
    console->Printf(KFormatBufLenSizeMax,
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
                // Now insert another descriptor at pos 2
                // to give "XijklmnYZabc"
                //
    _LIT(KTextijklmn,"ijklmn");
    buf.Insert(1,KTextijklmn);

                // Show result
    console->Printf(KFormatBufLenSizeMax,
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
                                      
    
                // Insertion point out of range
                // (> current length of descriptor)
                // 
                // Remove the "//" marks on the next line
                // to see this panic
    //_LIT(KTxtqwerty,"qwerty");
    //buf.Insert(buf.Length()+1,KTxtqwerty);
    
    
                // Resulting length of data
                // is > maximum length.
                // 
                // Remove the "//" marks on the next line
                // to see this panic
    //_LIT(KTxtatoz,"abcdefghijklmnopqrstuvwxyz");
    //buf.Insert(12,KTxtatoz);
    
    
                // Now delete the 3 data 
                // items (characters) at the start
                // of buf to give "klmnYZabc"
    buf.Delete(0,3);

                // Show result
    console->Printf(KFormatBufLenSizeMax,
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
                // Now delete the 4 data items (characters) at
                // position 4 to give "klmnc"
                //
    buf.Delete(4,4);
    
                // Show result
    console->Printf(KFormatBufLenSizeMax,
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
               // An excessive length for deletion is 
               // truncated to a sensible value. Deletes 
               // all the data starting at pos 1 to 
               // give "k"
               // (Note that the length actually
                //  deleted is 4 NOT 25000).
                            
    buf.Delete(1,25000);
    
                // Show result
    console->Printf(KFormatBufLenSizeMax,
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
         
            //              
            // TrimLeft() & TrimRight()  * * * * * * * * *
            //
    _LIT(KTitleTrimLeft,"\n--->TrimLeft() & TrimRight()");
    console->Printf(KTitleTrimLeft);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // set buf up and show the detail
    buf.Fill(' ',18);
    buf.Replace(3,(&KTextHelloWorld)->Length(),KTextHelloWorld);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // Remove left hand spaces     
    buf.TrimLeft(); 
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // Remove right hand spaces    
    buf.TrimRight();    
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // Trim() removes both left and right
                // hand spaces 

         
           //                
            // FillZ() & Fill()  * * * * * * * * * *  
            //
    _LIT(KTitleFill,"\n--->FillZ() & Fill()");
    console->Printf(KTitleFill);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();
                
                // Set current length of buf
                // Fillz() fills buf up to its current length
                // with 0x00.
    buf.SetLength(8);
    buf.FillZ();

                // Show it
    counter = buf.Length();
    for (index = 0; index < counter; index++)
        console->Printf(KFormatCommon,buf[index]);
        
    console->Printf(KFormatLenSizeMax,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // Fills buf up to its current length 
                // with 'A'
    buf.Fill('A');
    
                // show it
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
            //              
            // Num(), NumUC(), AppendNum() & AppendNumUC()
            //
    _LIT(KTitleNum,"\n--->Num(), NumUC(), AppendNum()");
    console->Printf(KTitleNum);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // convert a signed integer to 
                // decimal characters
    buf.Num(-176);

                // show it
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // convert another signed integer
    buf.Num(12345);

                // show it
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

                // convert an unsigned integer
    TUint nosign = 176;
    
                // ... into decimal characters (the default,
                // if not explicitly specified)
    buf.Num(nosign);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
                   
                // ... into binary characters
    buf.Num(nosign,EBinary);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
                // ... into octal characters
    buf.Num(nosign,EOctal);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
                // ... into lower case hex characters
    buf.Num(nosign,EHex);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );                  
    
                // ... into upper case hex characters
    buf.NumUC(nosign,EHex);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
            
                // Append functions the same, except 
                // they append the converted data.
                // Put "xyz" into the descriptor, convert
                // and concatenate the variations.

    _LIT(KTextxyz,"xyz");             
    buf = KTextxyz;

    buf.AppendNum(nosign);
    buf.AppendNum(nosign,EBinary);
    buf.AppendNum(nosign,EOctal);
    buf.AppendNum(nosign,EHex);
    buf.AppendNumUC(nosign,EHex);
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
                          
            //              
            // Justify() & AppendJustify()* * * 
            //
    _LIT(KTitleJustify,"\n--->Justify() & AppendJustify()");
    console->Printf(KTitleJustify);
    console->Printf(KPressAnyKeyToContinue);
    
    console->Getch();

                // source descriptor for this example has
                // length 12. 
    TBufC<40> src(KTextHelloWorld);
                
                // target field in buf has width 16 (NB this
                // is greater than the length of the descriptor 
                // src).
                // src is copied into target field, aligned left 
                // and padded with '@' characters.
                //
                // length of buf becomes the same as the 
                // specified width, i.e 16 
    buf.Justify(src,16,ELeft,'@');
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
                // target field in buf has width 16 (NB this
                // is greater than the length of the descriptor
                // src).
                // src is copied into target field, aligned centre 
                // and padded with '@' characters
                //
                // length of buf becomes the same as the
                // specified width, i.e 16 
    buf.Justify(src,16,ECenter,'@');
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
                // target field in buf has width 10 (NB this
                // is smaller than the length of the descriptor
                // src).
                // src is copied into target field but truncated
                // to 10 characters and, therefore, alignment and 
                // padding information not used.
                //
                // length of buf becomes the same as the 
                // width, i.e 10 
    buf.Justify(src,10,ECenter,'@');
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
        
                // target field in buf is set to the length of
                // the descriptor src (whatever it currently is)
                //
                // src copied into target field. No padding and
                // no truncatiuon needed and so the
                // alignment and padding information is not used.
                //
                // length of buf becomes the same as the length
                // of src i.e 12 
    buf.Justify(src,KDefaultJustifyWidth,ECenter,'@');
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );
    
    
    
                // implied width > maximum length of buf.
                // 
                // Remove the "//" marks on the next two lines
                // to see this panic
    //_LIT(KTxtPanicCausingText,"Panic causing text because length > 32");
    //src = KTxtPanicCausingText;
    //buf.Justify(src,KDefaultJustifyWidth,ECenter,'@' );
    

     
                // explicit width > maximum length of buf
                // 
                // Remove the "//" marks on the next line
                // to see this panic
    //buf.Justify(src,33,ECenter,'@');
    

                // AppendJustify() is  similar but target 
                // field appended to descriptor.
                //
                // Target field in buf has width 16 
                // (NB greater than length of descriptor 
                // src) and is appended to existing content
                // of buf.
                // src copied into target field, 
                // aligned left and padded with '@' 
                // characters
                //
                // Resulting length of buf is the length
                // of "ABCD" plus the width of the target
                // field (16) giving a value of 20.
    _LIT(KTextABCD,"ABCD");
    buf = KTextABCD;
    buf.AppendJustify(src,16,ELeft,'@');
    console->Printf(KFormatBufLenSizeMax,  
                    &buf,
                    buf.Length(),
                    buf.Size(),
                    buf.MaxLength()
                   );

           //                
            // Format() & AppendFormat() * * * 
            //
    _LIT(KTitleFormatAndAppendFormat,"\n--->Format() & AppendFormat()");
    console->Printf(KTitleFormatAndAppendFormat);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // use tgt as a target descriptor to show 
                // the results of format()
    TBuf<128> tgt;
    
                // The basic %<type> format.
                // Interprets the arguments as signed/unsigned
                // integers and generates the appropriate
                // character representations. The characters only
                // occupy the space needed to represent them.
                //
                // Generates:"1000001 A 65 101 65 41"
                //
                // format string is:
                // "%b %c %d %o %u %x"

    _LIT(KFormat1,"%b %c %d %o %u %x");
    tgt.Format(KFormat1,65,65,65,65,65,65);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );            

                // Interprets the argument as an unsigned
                // integer; the generated (hex) characters are
                // right aligned and padded to the left
                // with '0' to make a total of 4 characters.
                //
                // Generates:"0041"
                //
                // format string is:
                // "%04x"
    _LIT(KFormat2,"%04x");
    tgt.Format(KFormat2,65);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );
                                          
                // Interprets the argument as an unsigned
                // integer;the generated (hex) characters are
                // right aligned and padded to the left with 
                // blanks to make a total of 4 characters.
                //
                // Generates:"  41"
                //
                // format string is:
                // "%4x"
    tgt.Format(KFormatfourex,65);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );            
                                          
                // Interprets the argument as an unsigned
                // integer; the generated (hex) characters are
                // right aligned and padded to the left with 
                // blanks to make a total of 4 characters.
                //
                // Generates:"1fff" 
                //
                // NB the correct hex value is "1ffff"
                // but width specified as 4 resulting 
                // in TRUNCATION.
                // 
                //
                // format string is:
                // "%4x"
    tgt.Format(KFormatfourex,131071);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );                                              
    
                // The '*' means that the width of the output
                // is taken from the 1st argument in the list; 
                // Interprets the 2nd argument as an unsigned
                // integer.
                // The generated (hex) characters are right 
                // aligned and padded to the left with blanks
                // to make a total of 4 characters.
                //
                // Generates:"  41"
                //
                // format string is:
                // "%*x"
    _LIT(KFormat4,"%*x");
    tgt.Format(KFormat4,4,65);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );            
        
                // Interprets the 1st argument as a signed
                // integer. 
                //
                // The generated (decimal) characters are 
                // right aligned and padded to the left 
                // with '$' to make a total of 4 characters.
                //
                // These are then followed by the
                // 4 characters ".00 "
                //                                             
                // Interprets the 2nd argument as a descriptor.
                // The characters within the descriptor are
                // appended to those already generated.
                //
                // Generates:"$$65.00 over"
                //
                // Format string is:
                // "%+$4d.00 %S"
                //
    
    _LIT(KTextover,"over");
    _LIT(KFormat5,"%+$4d.00 %S");
    tgt.Format(KFormat5,65,&KTextover);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );
    
    
                // The * means that the width of the 
                // output is taken from the 1st argument 
                // in the list.
                //
                // Interprets the 2nd argument as a descriptor.
                // The characters copied from it are right 
                // aligned and padded on the left with
                // '0' characters
                //
                // Generates:"000000fred"
                //
                // Format string is:
                // "%+0*S"
                //
    
    _LIT(KTextfred,"fred");
    _LIT(KFormat6,"%+0*S");
    tgt.Format(KFormat6,10,&KTextfred);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );                          
    

                // The * means that the fill character is 
                // taken from the 1st argument in the list.
                //
                // Interprets the 2nd argument as an unsigned
                // integer.
                // The generated characters are centrally 
                // aligned and padded on the left and right
                // with '*' to make 6 characters.
                //
                // Generates:"**41**"
                //
                // Format string is:
                // "%=*6x"
                //
    
    _LIT(KFormat7,"%=*6x");
    tgt.Format(KFormat7,'*',65);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );
                                                
                // The 1st '*' means that the fill character 
                // is taken from the 1st argument in the list.
                //
                // The 2nd '*' means that the width is taken
                // from the 2nd argument in the list
                //
                // Interprets the 3rd argument as a signed
                // integer.
                // The generated characters are right aligned
                // and padded on the left with '.' to make
                // 10 characters.
                //
                // Generates:".......-65"
                //
                // Format string is:
                // "%+**d"
                //
        
    _LIT(KFormat8,"%+**d");
    tgt.Format(KFormat8,'.',10,(-65));
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );
                                               
                // Same as the previous example but the 
                // characters are left aligned and padded to
                // the right with '.' characters.
                //
                // Generates:"-65......."              
                //
                // Format string is:
                // "%-**d"
                //
    
    _LIT(KFormat9,"%-**d");       
    tgt.Format(KFormat9,'.',10,(-65));
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );                                                  
                              
                // Generates 6 fill characters 'A'.
                // Makes no use of the argument list.
                //
                // Generates: "AAAAAA"                
                //
                // Format string is:
                // "%-A6p"
                //
    
    _LIT(KFormat10,"%-A6p");      
    tgt.Format(KFormat10,65);
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );

                 // Interpret the argument as a TInt64 type.         
    _LIT(KFormat10a,"%Li");    
    
    TInt64   var(65);
    tgt.Format(KFormat10a,var);
    
    console->Printf(KFormatBufLenSizeMax,  
                    &tgt,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                    );
        



                // Interpret the argument as an unsigned integer
                // and convert to a two byte numeric 
                // representation (most significant byte first)
                //
                // So 4660 = 0x1234 => 1st byte contains 0x12
                //                     2nd byte contains 0x34 
                //
                // NB This is same for both ASCII & UNICODE build
                //
                // Format string is:
                // "%m"
                //
     
    _LIT(KFormat11,"%m");
    tgt.Format(KFormat11,4660);
    
    counter = tgt.Length();
    for (index = 0; index < counter; index++)
        console->Printf(KFormatCommon,tgt[index]);
        
    console->Printf(KFormatLenSizeMax,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );





                // Interpret the argument as an unsigned integer
                // and convert to a four byte numeric 
                // representation (most significant byte first)
                //
                // So 4660 = 0x1234 => 1st byte contains 0x00
                //                     2nd byte contains 0x00 
                //                     3rd byte contains 0x12
                //                     4th byte contains 0x34
                // NB This is same for both ASCII & UNICODE build   
                //
                // Format string is:
                // "%M"
                //
    
    _LIT(KFormat12,"%M");
    tgt.Format(KFormat12,4660);                                
    
    counter = tgt.Length();   
    for (index = 0; index < counter; index++)
        console->Printf(KFormatCommon,tgt[index]);
        
    console->Printf(KFormatLenSizeMax,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );

                // Interpret the argument as an unsigned integer
                // and convert to a two byte numeric 
                // representation (least significant byte first)
                //
                // So 4660 = 0x1234 => 1st byte contains 0x34
                //                     2nd byte contains 0x12 
                //
                // NB This is same for both ASCII & UNICODE build
                //
                // Format string is:
                // "%w"
                //
      
    _LIT(KFormat13,"%w");
    tgt.Format(KFormat13,4660);
    
    counter = tgt.Length();
    for (index = 0; index < counter; index++)
        console->Printf(KFormatCommon,tgt[index]);
        
    console->Printf(KFormatLenSizeMax,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );

                // Interpret the argument as an unsigned integer
                // and convert to a four byte numeric 
                // representation (least significant byte first)
                //
                // So 4660 = 0x1234 => 1st byte contains 0x34
                //                     2nd byte contains 0x12 
                //                     3rd byte contains 0x00
                //                     4th byte contains 0x00
                // NB This is same for both ASCII & UNICODE build   
                //
                // Format string is:
                // "%W"
                //

    _LIT(KFormat14,"%W");
    tgt.Format(KFormat14,4660);                                
    
    counter = tgt.Length();   
    for (index = 0; index < counter; index++)
        console->Printf(KFormatCommon,tgt[index]);
        
    console->Printf(KFormatLenSizeMax,
                    tgt.Length(),
                    tgt.Size(),
                    tgt.MaxLength()
                   );
    
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();
    
    
           //                
            // AppendFormat() illustrating use of the
            // overflow handler 
            //
    _LIT(KTitleOverflowHandler,"\n--->AppendFormat() & the overflow handler");
    console->Printf(KTitleOverflowHandler);
    console->Printf(KPressAnyKeyToContinue);
    console->Getch();

                // use the TestOverflow class as the overflow 
                // handler
    TBuf<16>     overtgt;
    TestOverflow theoverflow;
    
                // prime "overtgt" with data (of length 14)
    _LIT(KTextabcdefghijklmn,"abcdefghijklmn");
    overtgt = KTextabcdefghijklmn;

                // Format string contains just literal
                // text and no embedded commands.
                // Length of literal text is 3
                // 14+3 > max length of "overtgt" and 
                // so theoverflow.Overflow() will be invoked
    
    _LIT(KTextopq,"opq");
    overtgt.AppendFormat(KTextopq,&theoverflow);

                // NB omitting the 2nd parameter, giving:
                // overtgt.AppendFormat(KTextopq);
                // results in a panic.
    }
    

Description

The example shows the usage of descriptor functions which can modify the descriptor. These are the functions defined and implemented by the TDes class: for example SetLength(), Copy() and Insert().


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


NonModifier: non-modifiable descriptors


Example code

Found in: examples\Base\BufsAndStrings\Desc\NonModifier

// NonModifier.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate some of the non-modifying member
// functions of descriptors.

#include "CommonFramework.h"

//
// Common literal text
//
_LIT(KTxtPressToContinue," (press any key to continue)\n");
_LIT(KTxtnotfound,"NOT FOUND");
_LIT(KTxtfound,"found");
_LIT(KTxtlessthan,"  is less than     ");
_LIT(KTxtgreaterthan,"  is greater than  ");
_LIT(KTxtequalto,"  is equal to      ");

//
// Common Format strings
//
_LIT(KCommonFormat2,"Length()=%d; Size()=%d\n");
_LIT(KCommonFormat8,"\"%S\"  Char %c is at pos %d (%S)\n");
_LIT(KCommonFormat9,"%- 8S   pos %2d  (%S)\n");
//
// Compare strings
//
_LIT(KTxtCompstr1,"Hello World!@@");
_LIT(KTxtCompstr2,"Hello");
_LIT(KTxtCompstr3,"Hello Worl");
_LIT(KTxtCompstr4,"Hello World!");
_LIT(KTxtCompstr5,"hello world!");
_LIT(KTxtCompstr6,"Hello World ");
_LIT(KTxtCompstr7,"Hello World@");

//
// Match strings
//
_LIT(KTxtMatchstr1,"*World*");
_LIT(KTxtMatchstr2,"*W?rld*");
_LIT(KTxtMatchstr3,"Wor*");
_LIT(KTxtMatchstr4,"Hello");
_LIT(KTxtMatchstr5,"*W*");
_LIT(KTxtMatchstr6,"hello*");
_LIT(KTxtMatchstr7,"*");


// Do the example
LOCAL_C void doExampleL()
    {
    TInt            index;
    TInt            pos;
    TPtrC           genptr;
                                                              
                // Use a TBufC to demonstrate some of these
                // and use the standard "Hello World!" text
    _LIT(KTxtHelloWorld,"Hello World!");
    const TBufC<16> bufc(KTxtHelloWorld);
    
            //              
            // Right() & Mid()  * * * * * * * * * * * *  
            //  
    _LIT(KTxtRightMid,"\n--->Right() & Mid()\n");
    console->Printf(KTxtRightMid);

                // Look at the content of bufc
    _LIT(KFormat1,"      TBufC: \"%S\"; Ptr()=%x; ");
    console->Printf(KFormat1,&bufc,bufc.Ptr());

    console->Printf(KCommonFormat2,bufc.Length(),bufc.Size());

                // Construct a TPtrC to represent the right
                // hand 5 data items. The function Left()
                // is similar.
    TPtrC ptrc1 = bufc.Right(5);

                // ptrc's data is "orld!"
                // Length of ptrc is 5
                // ptrc's data area address = bufc's data area
                // address + 7
    _LIT(KFormat3,"Right TPtrC: \"%S\"; Ptr()=%x; ");
    console->Printf(KFormat3,&ptrc1,ptrc1.Ptr());
    console->Printf(KCommonFormat2,ptrc1.Length(),ptrc1.Size());

                // Construct a TPtrC to represent the 6 data
                // items offset 3 from the start of bufc's
                // data area. 
    TPtrC ptrc2 = bufc.Mid(3,6);  
    
                // ptrc's data is "lo Wor"
                // Length of ptrc is 6
                // ptrc's data area address = buf's data area
                // address + 3
    _LIT(KFormat4,"  Mid TPtrC: \"%S\"; Ptr()=%x; ");
    console->Printf(KFormat4,&ptrc2,ptrc2.Ptr());
    console->Printf(KCommonFormat2,ptrc2.Length(),ptrc2.Size());
                // In practice, there is often no need to 
                // assign the returned TPtrC to another TPtrC.
                // For example, the following code puts a 
                // value of 3 in pos; this is the offset
                // of char 'W' within the chars "lo Wor"  
                // (see later for more detail on Locate())
                
    pos = (bufc.Mid(3,6)).Locate('W');
    _LIT(KFormat5,"(bufc.Mid(3,6)).Locate('W') returns %d\n");
    console->Printf(KFormat5,pos);

                // Want the 13 right hand data items.
                // This is > current length of bufc
                // causing panic !!
                // 
                // Remove the "//" marks on the next line
                // to see this happen
    //TPtrC ptrc3 = bufc.Right(13);
    
            //              
            // Compare() & CompareF()   * * * * * * * * *
            //
    _LIT(KTxtCompare,"\n--->Compare() & CompareF()");
    console->Printf(KTxtCompare);
    console->Printf(KTxtPressToContinue);  //" (press any key to continue)\n"
    console->Getch();

                // Can compare any kind of data.
                // For binary data just use Compare().
                // For text use Compare(), CompareF() or 
                // CompareC(). Using the Compare() function,
                // case is important so that, below, the 4th 
                // comparison is equal but the 5th is unequal.
    
    const TBufC<16> compstr[7] =  {*&KTxtCompstr1, // "Hello World!@@"
                                   *&KTxtCompstr2, // "Hello"
                                   *&KTxtCompstr3, // "Hello Worl"
                                   *&KTxtCompstr4, // "Hello World!"
                                   *&KTxtCompstr5, // "hello world!"
                                   *&KTxtCompstr6, // "Hello World "
                                   *&KTxtCompstr7  // "Hello World@"
                                  };

    for (index = 0; index < 7; index++)
        {
        
        if ( (bufc.Compare(compstr[index])) < 0 )
            genptr.Set(KTxtlessthan);
        else if ( (bufc.Compare(compstr[index])) > 0)
                genptr.Set(KTxtgreaterthan);
             else genptr.Set(KTxtequalto);
        _LIT(KFormat6,"\"%S\"%S\"%S\"\n");        
        console->Printf(KFormat6,&bufc,&genptr,&compstr[index]);
        }

                // CompareF() ignores case so that now,
                // both the 4th and the 5th comparsions
                // are equal.
                // NOTE that the behaviour of CompareF() is locale dependent.
    for (index = 3; index < 5; index++)
        {
        if ( (bufc.CompareF(compstr[index])) < 0 )
            genptr.Set(KTxtlessthan);
        else if ( (bufc.CompareF(compstr[index])) > 0)
                genptr.Set(KTxtgreaterthan);
             else genptr.Set(KTxtequalto);
        _LIT(KTxtusingCF," (using CompareF())");
        _LIT(KFormat7,"\"%S\"%S\"%S\"%S\n");
        console->Printf(KFormat7,&bufc,&genptr,&compstr[index],&KTxtusingCF);
        }

            //              
            // Locate(), LocateF(), LocateReverse()     * * *
            //
            // NOTE that the behaviour of LocateF() is locale dependent.
    _LIT(KTxtLocate,"\n--->Locate(), LocateF() & LocateReverse()");
    console->Printf(KTxtLocate);
    console->Printf(KTxtPressToContinue);  //" (press any key to continue)\n"
    console->Getch();
                
                // Locate the positions (i.e. the offsets) of
                // these characters in "Hello World!"              
    TChar ch[4] = {'H', '!', 'o', 'w'};
                            
                // using Locate().
                // Note that 'w' is not found because the
                // function is case sensitive
    _LIT(KTxtUsingLocate,"using Locate() \n");
    console->Printf(KTxtUsingLocate);
    for (index = 0  ; index < 4; index++)
        {
        pos = bufc.Locate(ch[index]);

        if (pos < 0)
            genptr.Set(KTxtnotfound);
        else 
            genptr.Set(KTxtfound);

        console->Printf(KCommonFormat8,&bufc,TUint(ch[index]),pos,&genptr);
        }

                // using LocateF()
                // Note that 'w' is found because the
                // function is NOT case sensitive.
                //
                // NOTE that the behaviour of LocateF() is locale dependent.
    _LIT(KTxtUsingLocateF,"using LocateF() \n");
    console->Printf(KTxtUsingLocateF);
    for (index = 0  ; index < 4; index++)
        {
        pos = bufc.LocateF(ch[index]);

        if (pos < 0)
            genptr.Set(KTxtnotfound);
        else 
            genptr.Set(KTxtfound);

        console->Printf(KCommonFormat8,&bufc,TUint(ch[index]),pos,&genptr); 
        }
    
            // using LocateReverse()
            // Note that the 2nd char 'o' is found this time
    _LIT(KTxtUsingLocateReverse,"using LocateReverse() \n");
    console->Printf(KTxtUsingLocateReverse);
    for (index = 0  ; index < 4; index++)
        {
        pos = bufc.LocateReverse(ch[index]);

        if (pos < 0)
            genptr.Set(KTxtnotfound);
        else 
            genptr.Set(KTxtfound);

        console->Printf(KCommonFormat8,&bufc,TUint(ch[index]),pos,&genptr);
        }
        
            //              
            // Match() & MatchF()   * * * * * * *
            //
            //
            // NOTE that the behaviour of MatchF() is locale dependent.
    _LIT(KTxtMatch,"\n--->Match()");
    console->Printf(KTxtMatch);
    console->Printf(KTxtPressToContinue);  //" (press any key to continue)\n"
    console->Getch();

    
    TBufC<8> matchstr[7] =  {*&KTxtMatchstr1, // "*World*"
                             *&KTxtMatchstr2, // "*W?rld*"
                             *&KTxtMatchstr3, // "Wor*"
                             *&KTxtMatchstr4, // "Hello"
                             *&KTxtMatchstr5, // "*W*"
                             *&KTxtMatchstr6, // "hello*"
                             *&KTxtMatchstr7  // "*" 
                            };


    _LIT(KFormat10,"\"%S\"\n");
    console->Printf(KFormat10,&bufc);
             
               // using Match()
    for (index = 0  ; index < 7; index++)
        {
        pos = bufc.Match(matchstr[index]);

        if (pos < 0)
            genptr.Set(KTxtnotfound);
        else 
            genptr.Set(KTxtfound);
        
        console->Printf(KCommonFormat9,&matchstr[index],pos,&genptr); 
        }

                // using MatchF()
                //   
                // Note the different result when matching 
                // the 6th string, where case is ignored.
                //
                // NOTE that the behaviour of MatchF() is locale dependent.
    _LIT(KTxtMatchF,"\n--->MatchF()");
    console->Printf(KTxtMatchF);
    console->Printf(KTxtPressToContinue);  //" (press any key to continue)\n"
    console->Getch();
    
    for (index = 0  ; index < 7; index++)
        {
        pos = bufc.MatchF(matchstr[index]);

        if (pos < 0)
            genptr.Set(KTxtnotfound);
        else 
            genptr.Set(KTxtfound);

        console->Printf(KCommonFormat9,&matchstr[index],pos,&genptr); 
        }
    }





    
    

Description

The example shows the use of descriptor functions which do not modify the descriptor. These are the functions defined and implemented by the TDesC class; for example Length(), Size() and Compare().


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


Pointer: basic idea of pointer descriptors


Example code

Found in: examples\Base\BufsAndStrings\Desc\Pointer

// Pointer.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// Examples to demonstrate the basic ideas of
// pointer descriptors. 
//

#include "CommonFramework.h"

//
// Common literal text
//
_LIT(KTxtHiTHere,"Hi there");
_LIT(KTxtHaveNiceDay,"Have a nice day!");

//
// Common format strings
//
_LIT(KCommonFormat1,"\"%s\"\n");
_LIT(KCommonFormat3,"length=%d; size=%d;\n");
_LIT(KCommonFormat5,"Ptr()=%x; Length()=%d; Size()=%d\n");
_LIT(KCommonFormat16,"MaxLength()=%d\n");
_LIT(KCommonFormat17,"\"%S\"; ");
_LIT(KCommonFormat18,"Length()=%d; Size()=%d; ");

// Do the example
LOCAL_C void doExampleL()
    {
                    // Define a constant C style (ASCII) string
    const TText8* cstr8 = (TText8*)"Hello World!";

                  // Look at it.

    TBuf<12> temp;
    temp.Copy(TPtrC8(cstr8));
    console->Printf(temp);

                // A TPtrC8 descriptor represents the
                // ASCII text; contrast this with the
                // basic C string  
    TPtrC8 ptrC8(cstr8);

                // Look at:
                //   1. Address of C string
                //   2. Length of the C string
                //   3. Size of the string.
                // Size is 13 bytes to allow for 
                // the terminating NULL.
                // 
    _LIT(KFormat2,"\nNarrow C string at %x; ");
    console->Printf(KFormat2,cstr8);
    console->Printf(KCommonFormat3,12,sizeof("Hello World!"));

                // Look at:
                //   1. Address of descriptor
                //   2. Address of descriptor data area
                //   3. Length  of descriptor
                //   4. Size of descriptor
                // Address of descriptor data area is the 
                // same as the address of the C string. 
                // The Size of the descriptor data is only
                // 12 bytes (1 byte for each character).
    _LIT(KFormat4,"8-bit pointer-descriptor at %x; ");
    console->Printf(KFormat4,&ptrC8);
    console->Printf(KCommonFormat5,ptrC8.Ptr(),ptrC8.Length(),ptrC8.Size());     
                                
        
                // Define a constant C style (Wide) string
    const TText16*  cstr16 = (TText16*)L"Hello World!";

                // A TPtrC16 descriptor represents the
                // wide (i.e. double-byte character) text;
                // contrast this with the basic C string.  
    TPtrC16 ptrC16(cstr16);
    
    _LIT(KFormat7,"\nWide C string at %x; ");
    console->Printf(KFormat7,cstr16);
    console->Printf(KCommonFormat3,12,sizeof(L"Hello World!"));
    
                // Look at:
                //   1. Address of descriptor
                //   2. Address of descriptor data area
                //   3. Length  of descriptor
                //   4. Size of descriptor
                // Address of descriptor data area is the
                // same as the address of the C string.
                // The size of descriptor data is only
                // 24 bytes (2 bytes for each character).
    _LIT(KFormat6,"16-bit pointer-descriptor at %x; ");
    console->Printf(KFormat6,&ptrC16);
    console->Printf(KCommonFormat5,ptrC16.Ptr(),ptrC16.Length(),ptrC16.Size());      
    
        
                // Use the _S macro to define a constant 
                // C style string of the appropriate width.
                // The TText variant is defined at build
                // time    as  TText16 
                // (In earlier times this could also have been TText8,
                //  but in all current versions, TText16 is the standard).
    const TText* cstr = _S("Hello World!"); 

                // TPtrC descriptor represents the text;
                // the TPtrC variant is defined at build 
                // time as TPtrC16.
    TPtrC ptrc(cstr);
    
    _LIT(KFormat8,"\nBuild-dependent TText at %x; ");
    console->Printf(KFormat8,cstr);
    console->Printf(KCommonFormat3,12,sizeof( 
                                       #ifdef _UNICODE
                                      L"Hello world!"
                                      #else
                                      "Hello world!"
                                      #endif
                                       )
                   );
    
               // Look at descriptor basics.
    _LIT(KTxtBuildDependentptdesc,"Build-dependent pointer-descriptor");
    console->Printf(KTxtBuildDependentptdesc);
    
    _LIT(KFormat9," at %x; ");
    console->Printf(KFormat9,&ptrc);
    _LIT(KFormat10,"Ptr()=%x;\n");
    console->Printf(KFormat10,ptrc.Ptr());
    _LIT(KFormat11," Length()=%d; Size()=%d\n");
    console->Printf(KFormat11,ptrc.Length(),ptrc.Size());

                // The _LIT macro is most useful. It constructs
                // a family of constant descriptor classes TLitC<Tint>. 
                // The constant generated by the _LIT macro:
                //   1. can be passed as 'const TDesC&' type
                //   2. has an address-of operator 'operator&()' which returns a 'const TDesC*' type
                //   3. can be passed as a TRefByValue<const TDesC>
                //
                // The _L macro constructs a TPtrC but should be avoided 
                // where possible on the grounds of efficiency.
                // Use the _LIT macro instead.
                
    console->Printf(_L("\nThe _L macro constructs a TPtrC"));
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    
    _LIT(KTxtTPtrBasicConcepts,"\n-->TPtr basic concepts");
    console->Printf(KTxtTPtrBasicConcepts);
    _LIT(KTxtPressToContinue," (press any key to continue)\n");
    console->Printf(KTxtPressToContinue);
    console->Getch();
                    
                // Set up an area and initialise to a 
                // C style string (including the NULL).
                // The need for the NULL forces cstr to
                // have a length of 16.
    TText str[16] =  {'H', 'a', 'v', 'e', ' ', 'a',
                      ' ', 'n', 'i', 'c', 'e',
                      ' ', 'd', 'a', 'y', '\0'};

                // Look at it.
    console->Printf(KCommonFormat1,&str[0]);

               // TPtr descriptor represents the text.
               // Descriptor length is 15 but max length
               // is 16. The descriptor does not need the
               // terminating NULL, so in this example,
               // the last data position is spare. 
   TPtr  ptr(&str[0],15,16);

                // Look at:
                //   1. Address of the C string
                //   2. Length of the C string
                //   3. Size of the string
                // Size is 16 bytes to allow for
                // the terminating NULL.
    _LIT(KFormat12,"C string at %x; ");
    console->Printf(KFormat12,str);
    _LIT(KFormat13,"length=%d; size=%d\n");
    console->Printf(KFormat13,15,sizeof(str));

               // Look at:
                //   1. Address of descriptor
                //   2. Address of descriptor area
                //   3. Length of descriptor
                //   4. Size of descriptor
                //   5. Max length of descriptor 
                // Address of descriptor data area is the 
                // same as the address of cstr[]. The
                // descriptor length is 15 but the maximum
                // length is 16.
    _LIT(KFormat14,"Descriptor at %x; ");
    console->Printf(KFormat14,&ptr);
    _LIT(KFormat15,"Ptr()=%x; Length()=%d; Size()=%d; ");
    console->Printf(KFormat15,ptr.Ptr(),ptr.Length(),ptr.Size());
    console->Printf(KCommonFormat16,ptr.MaxLength());

                // The data can be replaced using the 
                // assignment operator. Note the reference to
                // the TLitC<> KTxtHiTHere constructed using the _LIT macro.
    ptr = KTxtHiTHere;             

                // Length of descriptor is now 8 but maximum
                // length remains at 16.
                // Size is 16 
                // Text in ptr's data area (i.e. in the area 
                // defined by str[]) is 
                // now "Hi there")
    console->Printf(KCommonFormat17,&ptr);
    console->Printf(KCommonFormat18,ptr.Length(),ptr.Size());
    console->Printf(KCommonFormat16,ptr.MaxLength());
                    
                // Length can be changed; data represented 
                // by the descriptor is now "Hi"
    ptr.SetLength(2);
                
    console->Printf(KCommonFormat17,&ptr);
    console->Printf(KCommonFormat18,ptr.Length(),ptr.Size());
    console->Printf(KCommonFormat16,ptr.MaxLength());

                // Length can be set to zero; NO data 
                // is now represented by the
                // descriptor but maximum length is still 16
    ptr.Zero();
    console->Printf(KCommonFormat17,&ptr);
    console->Printf(KCommonFormat18,ptr.Length(),ptr.Size());
    console->Printf(KCommonFormat16,ptr.MaxLength());

                // Replace text with text of length 16, 
                // the maximum. 
    ptr = KTxtHaveNiceDay;
   console->Printf(KCommonFormat17,&ptr);
    console->Printf(KCommonFormat18,ptr.Length(),ptr.Size());
    console->Printf(KCommonFormat16,ptr.MaxLength());

                // adding another character causes panic !!
                // length would be > maximum.
                // 
                // Remove the "//" marks on the next line
                // to see this happen
    //ptr.Append('@');
    }


    

Description

The example shows the basic idea of pointer descriptors and how they are used.


Classes used


Security issues

The example requires no specific capabilities in order to run - and does not demonstrate any security issues.

[Top]


WriteToFile: writes “Hello World!” to a file


Example code

Found in: examples\Base\BufsAndStrings\WriteToFiles

The files reproduced here are the main files contained in the examples directory. Some extra files may be needed to run the examples, and these will be found in the appropriate examples directory.

// WriteToFile.cpp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// This example writes the text "hello world!" to a file
// Use it as the basis of all examples which depend on just E32 and F32

#include "CommonFramework.h"
#include <f32file.h>

_LIT(KFileName,"WriteToFile.dat");
_LIT(KGreetingText,"Hello World!\n");

// Do the example
LOCAL_C void doExampleL()
    {
                                             // The file server session.
    RFs fsSession;                           
                                             // Connect to the file server session.
    User::LeaveIfError(fsSession.Connect()); 
    
                                             // create the private directory
                                             // on the writable drive
                                             // i.e. "\private\0FFFFF00\"
                                             // Note that the number 0FFFFF00 is the 
                                             // process security id taken from the 2nd UID
                                             // specified in the mmp file.
    fsSession.CreatePrivatePath(RFs::GetSystemDrive());
    
                                             // Set the session path to
                                             // this on the writable drive
    fsSession.SetSessionToPrivate(RFs::GetSystemDrive());
                                                 
                                             // Use this object to represent
                                             // the file to be written to.
    RFile file;                                  
                                                 
    User::LeaveIfError(file.Replace(fsSession,KFileName,EFileWrite|EFileStreamText));

        
                                             // Note that Write() requires a TDesC8
                                             // type so we need to construct an explicit
                                             // TDesC8 type to represent the data contained
                                             // in the standard (16-bit) descriptor.
    TPtrC8 representation((TUint8*)(&KGreetingText)->Ptr(), (&KGreetingText)->Size());
    
                                             // Write the text ...
    User::LeaveIfError(file.Write(representation));
                                                 
                                             // ... and commit the text.
    User::LeaveIfError(file.Flush());
    
    _LIT(KTxt1,"Data written to file\n");
    console->Printf(KTxt1);
                                             // Close file
    file.Close(); 
                                             // Delete file (remove comment if you want
                                             // to do this)
    //User::LeaveIfError(fsSession.Delete(KFileName));
    
                                                 // close file server session
    fsSession.Close(); 
    }
// WriteToFile.mmp
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

// using relative paths for source and userinclude directories

// No explicit capabilities required to run this.

// Please note that the 2nd UID listed here has not been
// allocated from the central pool of UI's and is not 
// guaranteed to be unique.
// The value is used for demonstration purposes only.
//

TARGET        WriteToFile.exe
TARGETTYPE    exe
UID           0 0x0FFFFF00
VENDORID      0x70000001

SOURCEPATH    .
SOURCE        WriteToFile.cpp

USERINCLUDE   .
USERINCLUDE   ..\..\CommonFramework
SYSTEMINCLUDE \Epoc32\include

LIBRARY       euser.lib efsrv.lib

CAPABILITY    None
// BLD.INF
// Component description file
//
// Copyright (C) Symbian Software Ltd 2000-2005.  All rights reserved.

PRJ_MMPFILES

WriteToFile.mmp

Description

This writes the text "Hello World!" to a file. It is used as the basis of all examples which depend on just the Base and the file server.


Classes used


Security issues

The example writes files to the executable's process private directory: C:\private\0FFFFF00\.

The second UID in the .mmp file is defined as 0x0FFFFF00 and this is used as the secure ID on which the name of the private directory is based.