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

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

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

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

The file-sharing server API that results in theabove server-side code being executed is shown below. Note that the fileserver session is also implicitly shared.TInt RFileHandleSharer::GetFileHandleWrite(TInt &aHandle){TPckgBuf<TInt> fileHandleBuf;TInt fileServerH = SendReceive(EMsgGetFileWrite,TIpcArgs(&fileHandleBuf));aHandle = fileHandleBuf() ;return fileServerH;}The client code to request and adopt the file handle is shown below:TInt RequestFileWrite(){TInt r;RFileHandleSharer handsvr;r = handsvr.Connect() ;if (r != KErrNone)return r;TInt fileHandle;TInt fileServerHandle = handsvr.GetFileHandleWrite(fileHandle);if (fileServerHandle < 0)return fileServerHandle;handsvr.Close() ;RFile file;r = file.AdoptFromServer(fileServerHandle, fileHandle);test(r == KErrNone);// file may now be used for access...}As we can see from the example above, the mechanism for sharing filehandles involves a client–server relationship between the two processessharing the file.RFileBufIf an application repeatedly requires small amounts of data from a file,it is advisable to read larger quantities from the file to an intermediatebuffer, from which the application can retrieve the small sections ofFILE SYSTEM SERVICES215data.

This prevents the application from making an excessive number ofIPC calls to the file server. Most file systems access data from sectorsof the underlying media. Each sector is typically aligned to a 512-byteboundary or some multiple. For an application author, it is more efficientto align your access to a 512-byte boundary where possible and practical,although this is not essential – any arbitrary byte of user data can be reador written to.In Symbian OS, the RFileBuf object allows you to combine accessto files with a buffer.

RFileBuf provides APIs similar to those of RFile;many of them are leaving functions. The following example shows howto create and use an RFileBuf:LOCAL_C void WriteToFileBufL(RFs& aFs, const TDesC& aFileName,const TDesC8& aData){RFileBuf buf(KBufSize);TInt err = buf.Open(aFs, aFileName, EFileWrite);if (err == KErrNotFound) // file does not exist, so create it{err = buf.Create(aFs, aFileName, EFileWrite);}User::LeaveIfError(err);CleanupStack::CleanupClosePushL(buf);TRequestStatus stat;buf.WriteL(aData, stat);User::WaitForRequest(stat);buf.SynchL() ;buf.Close() ;}Declaring an RFileBuf sets the size of the associated buffer.

If nosize is supplied, then a default size of 4 KB is used:RFileBuf buf(KBufSize);Next, we open the file we wish to associate with the buffer:TInt err = buf.Open(aFs, aFileName, EFileWrite);Each of the APIs that opens an RFile (Open(), Replace(),Create() and Temp()) is also supplied with RFileBuf. In addition,RFileBuf can use a pre-opened RFile object and call RFileBuf::Attach(RFile &aFile, TInt aPos=0) to associate it with the filebuffer. The RFile associated with a buffer can be obtained using RFileBuf::File() and can be detached (using RFileBuf::Detach())from the RFileBuf so that the buffer may be used with another file.216FILES AND THE FILE SYSTEMSeveral read and write functions are supplied to access the data in thefile:TRequestStatus stat;buf.WriteL(aData, stat);User::WaitForRequest(stat);The buffer and file can be synchronized by calling SyncL(), whichcauses the data to be flushed to file:buf.SynchL() ;Finally we close the file buffer, causing the memory resources to befreed and the RFile to be closed.

Any unwritten data is also written outto file at this point.buf.Close() ;ConclusionAs you can see from this brief discussion, RFile provides only the mostbasic of read and write functions, operating exclusively on 8-bit data.In consequence, RFile is not well suited to reading or writing the richvariety of data types that may be found in a Symbian OS application. Farfrom being an accident, this is a deliberate part of the design of SymbianOS, which uses streams to provide the necessary functionality for storingdata structures found in many applications.7.4 StreamsA Symbian OS stream is the external representation of one or moreobjects. The process of externalization involves writing an object’s datato a stream; the process of reading from a stream is termed internalization.The external representation may reside in one of a variety of media,including stores, files and memory.The external representation needs to be free of any peculiarities ofinternal storage – such as byte order and padding associated with dataalignment – that are required by the phone’s CPU, the C++ compiler orthe application’s implementation.

Clearly, it is meaningless to externalizea pointer; it must be replaced in the external representation by the datato which it points. The external representation of each item of datamust have an unambiguously defined length. This means that specialcare is needed when externalizing data types such as TInt, whoseinternal representation may vary in size between different processors orC++ compilers.STREAMS217Storing multiple data items (which may be from more than oneobject) in a single stream implies that they are placed in the streamin a specific order. Internalization code, which restores the objects byreading from the stream, must therefore follow exactly the same orderthat was used to externalize them. The implementation of internalizationand externalization functions define this order.Base ClassesThe concept of a stream is implemented in the two base classesRReadStream and RWriteStream, with concrete classes derived fromthem to support streams that reside in specific media.

For example,RFileWriteStream and RFileReadStream implement a streamthat resides in a file and RDesWriteStream and RDesReadStreamimplement a memory-resident stream whose memory is identified by adescriptor. In this chapter, the examples concentrate on file-based streamsbut the principles can be applied to streams using other media.The following code externalizes a TInt16 to a file, which is assumednot to exist before WriteToStreamFileL() is called:void WriteToStreamFileL(RFs& aFs, TDesC& aFileName, TInt16* aInt){RFileWriteStream writer;writer.PushL() ; // writer on cleanup stackUser::LeaveIfError(writer.Create(aFs, aFileName, EFileWrite));writer << *aInt;writer.CommitL() ;writer.Pop() ;writer.Release() ;}Since the only reference to the stream is on the stack, and the followingcode can leave, it is necessary to push the stream to the cleanup stack,using the stream’s (not the cleanup stack’s) PushL() function.

Once thefile has been created, the data is externalized by using operator <<. Afterwriting to the store, it is necessary to call the write stream’s CommitL()to ensure that any buffered data is written to the stream file. If a seriesof small contiguous operations have been carried out on the stream,they are not actually written to the underlying file; if they were, theimplementation would be rather inefficient.After CommitL(), you remove the stream from the cleanup stack,using the stream’s Pop() function. Finally, you need to call the stream’sRelease() function to close the stream and free the resources it hasbeen using.As we can see, the Create API takes a file name: the underlying streamclass creates a file used to store the data.

As much care should be takenwith the location of a stream or store file as with a raw RFile. Thesame platform security rules apply to all files owned by an application218FILES AND THE FILE SYSTEMregardless of whether they are used as raw files or for store or streampurposes.Instead of calling Pop() and Release(), you could make a singlecall to the cleanup stack’s PopAndDestroy(), which would achievethe same result. The following example uses that option; otherwise, thecode follows a similar pattern to the externalization example:void ReadFromStreamFileL(RFs& aFs, TDesC& aFileName, TInt16* aInt){RFileReadStream reader;reader.PushL() ; // reader on cleanup stackUser::LeaveIfError(reader.Open(aFs, aFileName, EFileRead));reader >> *aInt;CleanupStack::PopAndDestroy() ; // reader}Using << and >> OperatorsThese examples use the << operator to externalize the data and the >>operator to internalize it.

This is a common pattern that you can usefor:• all built-in types except those, such as TInt, whose size is unspecified• descriptors, although special techniques are needed to internalize thedata if the length can vary widely• any class that provides an implementation of ExternalizeL() andInternalizeL().In Symbian OS, a TInt is only specified to be at least 32 bits; itmay be longer, so externalizing it with << would produce an externalrepresentation of undetermined size. If you try to use <<, the compilerreports an error. Instead, use your knowledge of the data it containsto determine the size of the external representation.

For example, ifyou know that the value stored in a TInt can never exceed 16 bits,you can use RWriteStream’s WriteInt16L() to externalize it andRReadStream’s ReadInt16L() to internalize it:TInt i = 1234;writer.WriteInt16L(i);...TInt j = reader.ReadInt16L() ;If you use << to externalize a descriptor, the external representationcontains both the length and character width (8 or 16 bits) so that >> hassufficient information to perform the appropriate internalization:STREAMS219_LIT(KSampleText, "Hello world");TBuf<16> text = KSampleText;writer << text;...TBuf<16> newtext;reader >> newtext;This is fine, provided that the descriptor’s content is reasonably smalland known not to exceed a certain fixed length. If the descriptor canpotentially contain a large amount of data it would be wasteful alwaysto have to allow for the maximum.

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

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

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

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