Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 45

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 45 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 452018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 45)

As a single entity, a stream is useful for storing simpledata structures. However, for more complicated data or for a collectionof more than one set of data, we need to use a store. Table 7.2 showssome other stream types available in Symbian OS.7.5 StoresA Symbian OS store is a collection of streams, and is generally usedto implement the persistence of objects. The store class hierarchy isillustrated in Figure 7.2, where the concrete class names are in bold text.The base class for all stores is CStreamStore, whose API defines all thefunctionality needed to create and modify streams. The classes derivedfrom CStreamStore selectively implement the API according to theirneeds.As with streams, stores can reside in a variety of different media, suchas in memory (CBufStore) or in a stream, perhaps within another store(CEmbeddedStore), but the most commonly used medium is a file.The two file-based stores are CDirectFileStore and CPermanentFileStore.

The main way in which they differ from each other isSTORES225CStreamStoreCBufStoreCSecureStoreCPersistentStoreCEmbeddedStoreCFileStoreCDirectFileStoreCPermanentFileStoreFigure 7.2 Store class hierarchythat CPermanentFileStore allows the modification of streams afterthey have been written to the store, whereas CDirectFileStore doesnot.

This difference results in the stores being used to store persistent datafor two different types of application, depending on whether the storeor the application itself is considered to contain the primary copy of theapplication’s data.For an application such as a database, the primary copy of the data isthe database file itself. At any one time, the application typically holdsin memory only a small number of records from the file, in order todisplay or modify them. Any modified data is written back to the file,replacing the original version.

Such an application would use an instanceof CPermanentFileStore, with each record being stored in a separatestream.Other applications hold all their data in memory and, when necessary,load or save the data in its entirety. Such applications can use a CDirectFileStore since they never modify the content of the store butsimply replace the whole store with an updated version.Another distinction that can be made between the store types iswhether or not they are persistent.

A persistent store can be closed andopened again to read its content. The data in such a store thereforepersists after a program has closed it and even after the program itself hasterminated. A CBufStore is not persistent, since its in-memory data islost when the store is closed; a file-based store is persistent: the contentremains intact for the life of the file.The persistence of a store is implemented in the CPersistentStoreabstract class by defining a root stream, which is always accessible onopening the store. The root stream, in turn, contains a stream dictionarythat contains stream IDs – pointers to other streams – as illustrated in226FILES AND THE FILE SYSTEMroot streamstream2stream1Figure 7.3 Logical view of a persistent storeFigure 7.3.

The stream IDs provide access to the rest of the data in thestore.The physical structure of a direct file store consists of:• a 16-byte header containing three UIDs and a 4-byte checksum• a 4-byte stream position, indicating the start of the root stream, whichnormally contains the stream dictionary• a sequential list of the data for each stream, usually ending with theroot stream.The stream dictionary starts with an externalized TCardinality ofthe number of associations in the dictionary, followed by the associationsthemselves.

Each association occupies eight bytes and consists of astream’s UID and a 4-byte stream position, indicating the start of therelevant stream.TCardinality is a useful class that provides a compact externalization of numbers (such as the count of elements in an array) which,though potentially large, normally have small values.The structure of a permanent file store follows the same logical pattern,but the physical structure is more complex since it has to allow for recordsto be replaced or deleted.Creating a Persistent StoreThe following code illustrates how to create a persistent store.

Theexample creates a direct file store, but creating a permanent file storefollows a similar pattern.STORES227void CreateDirectFileStoreL(RFs& aFs, TDesC& aFileName, TUid aAppUid){CFileStore* store = CDirectFileStore::ReplaceLC(aFs, aFileName,EFileWrite);store->SetTypeL(TUidType(KDirectFileStoreLayoutUid, KUidAppDllDoc,aAppUid));CStreamDictionary* dictionary = CStreamDictionary::NewLC() ;RStoreWriteStream stream;TStreamId id = stream.CreateLC(*store);TInt16 i = 0x1234;stream << i;stream.CommitL() ;CleanupStack::PopAndDestroy() ; // streamdictionary->AssignL(aAppUid, id);RStoreWriteStream rootStream;TStreamId rootId = rootStream.CreateLC(*store);rootStream << *dictionary;rootStream.CommitL() ;CleanupStack::PopAndDestroy() ; // rootStreamCleanupStack::PopAndDestroy() ; // dictionarystore->SetRootL(rootId);store->CommitL() ;CleanupStack::PopAndDestroy() ; // store}To create the store itself we use:CFileStore* store = CDirectFileStore::ReplaceLC(aFs, aFileName,EFileWrite);The call to ReplaceLC() creates the file, if it does not exist, orreplaces an existing file.

With the direct store type, we cannot modify theindividual streams. In a real application, it might be more convenient tostore the pointer to the file store object in member data, rather than onthe stack.You need to set the store’s type, which we do by calling:store->SetTypeL(TUidType(KDirectFileStoreLayoutUid,KUidAppDllDoc, aAppUid));The three UIDs in the TUidType indicate, respectively, that the filecontains a direct file store, that the store is a document associated witha Symbian OS application and that the store is associated with theapplication whose UID is aAppUid. For the file to be recognized as228FILES AND THE FILE SYSTEMcontaining a direct file store, it is strictly only necessary to specify the firstUID, leaving the other two as KNullUid; including the other two allowsan application to be certain that it is opening the correct file.To create a permanent file store you would use:CFileStore* store = CPermanentFileStore::CreateLC(aFs, aFileName,EFileWrite);store->SetTypeL(TUidType(KPermanentFileStoreLayoutUid, KUidAppDllDoc,aAppUid));We have used the store’s CreateLC() function here, because youwould not normally want to replace an entire permanent file store.

It ismore likely that the permanent store, once created, would be opened foredit.Once you have created a file store, you can find its layout UID bycalling store->Layout() which, depending on the file store’s class,returns either KDirectFileStoreLayoutUid or KPermanentFileStoreLayoutUid.We then create a stream dictionary for later use:CStreamDictionary* dictionary = CStreamDictionary::NewLC() ;Creating, writing and closing a stream follows a similar pattern to theone we saw in Section 7.4:RStoreWriteStream stream;TStreamId id = stream.CreateLC(*store);TInt16 i = 0x1234;stream << i;stream.CommitL() ;CleanupStack::PopAndDestroy() ; // streamAn important difference is that, to write a stream to a store, youmust use an instance of RStoreWriteStream, whose CreateL()and CreateLC() functions return a TStreamId.

Once writing thestream is complete, you need to add an entry to the stream dictionary,making an association between the stream ID and an externally knownUID:dictionary->AssignL(aAppUid, id);If, as in this case, your application writes all the application’s documentdata into a single stream, it is safe to use the application’s UID.Once all the data streams have been written and added to the streamdictionary, you need to create a stream to contain the stream dictionary,and mark it as being the root stream:STORES229RStoreWriteStream rootStream;TStreamId rootId = rootStream.CreateLC(*store);rootStream << *dictionary;rootStream.CommitL() ;CleanupStack::PopAndDestroy() ; // rootStream...store->SetRootL(rootId);All that remains to be done is to commit all the changes made to thestore and then to free its resources which, in this case, is done by the callto the cleanup stack’s PopAndDestroy() function.store->CommitL() ;CleanupStack::PopAndDestroy() ; // storeIf the store is not on the cleanup stack, you should simply use:delete store;The store’s destructor takes care of closing the file and freeing anyother resources.Reading a Persistent StoreThe following code opens and reads the direct file store that was createdin the previous section.void ReadDirectFileStoreL(RFs& aFs, TDesC& aFileName, TUid aAppUid){CFileStore* store = CDirectFileStore::OpenLC(aFs, aFileName, EFileRead);CStreamDictionary* dictionary = CStreamDictionary::NewLC() ;RStoreReadStream rootStream;rootStream.OpenLC(*store, store->Root() );rootStream >> *dictionary;CleanupStack::PopAndDestroy() ; // rootStreamTStreamId id = dictionary->At(aAppUid);CleanupStack::PopAndDestroy() ; // dictionaryRStoreReadStream stream;stream.OpenLC(*store, id);TInt16 j;stream >> j;CleanupStack::PopAndDestroy() ; // streamCleanupStack::PopAndDestroy() ; // store}230FILES AND THE FILE SYSTEMAfter opening the file store for reading and creating a stream dictionary,you need to open the root stream, with:rootStream.OpenLC(*store, store->Root() );After that, you can internalize its content to the stream dictionary.

Wethen extract one or more stream IDs, using the dictionary’s At() function:TStreamId id = dictionary->At(aAppUid);The stream can now be opened using an RStoreReadStream andits contents may be internalized as appropriate for the application concerned. Finally, we clean up the store and stream items used.Permanent StoresIf you create a permanent file store you can, at a later time, reopen itand add new streams, or replace or delete existing streams. To ensurethat the modifications are made efficiently, replaced or deleted streamsare not physically removed from the store, so the store increases insize with each such change.

To counteract this, the stream store APIincludes functions to compact the store, by physically removing replacedor deleted streams.CompactL () is used to remove free space from the store file, effectivelyshrinking the size of the file. ReplaceL() is used to retrieve unusedspace within the store file making it available for use by new or modifiedstreams.

Both operations can take a prolonged period of time, dependingon the complexity and amount of change made to the store. To avoida long wait for compaction to complete, RStoreReclaim can beused to perform the task in smaller steps instead of one single step.RStoreReclaim must be open on the store object and released whenfinished with.Stores are transactional; that is, each change made by calling CommitL() can be considered atomic. Prior to the commit point, if it isno longer required, the change can be reversed by calling Revert().The store reverts to the same state it was in after the most recentCommitL() call.You need to be especially careful that you do not lose a reference toany stream within the store. This is analogous to a memory leak withinan application and results in the presence of a stream that can never beaccessed or removed.

Характеристики

Тип файла
PDF-файл
Размер
6,45 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее