quick_recipes (779892), страница 16

Файл №779892 quick_recipes (Symbian Books) 16 страницаquick_recipes (779892) страница 162018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

If you want to protect yourdata, use the \private\<SID> folder, where SID is the secure identifierfor your application (see Chapter 3, Section 3.12 for more information).Tip: The default file manager from S60 or UIQ phones cannot browsethrough all folders on the phone. The default S60 file manager canonly browse the c:\data folder. The default UIQ file manager canonly browser the c:\Media files folder.If you want to browse all folders on the phone, you will need athird-party file manager.

The following are available for S60 and UIQ:• Active File – see developer.symbian.com/wiki/display/pub/File+Browsers.• SwissManager – a free file manager for UIQ, www.cellphonesoft.com.• SysExplorer – a free file manager that supports S60 and UIQ,www.newlc.com.• Y-Browser – a free file manager for S60, www.drjukka.com.4.1.1.3Read Binary Data from a FileAmount of time required: 15 minutesLocation of example code: \Files\BinaryFileRequired library(s): efsrv.libRequired header file(s): f32file.hRequired platform security capability(s): NoneProblem: You want to read binary data from a file.FILE HANDLING83What may go wrong when you do this: The drive letter for the memorycard can differ between devices. For example, most S60 devices useE: as the drive letter for the memory card, while many UIQ devicesuse D:.

There are some devices that have a hard disk.You can check the drive type using the RFs::Drive() method.For example:TDriveInfo driveInfo;User::LeaveIfError(iCoeEnv->FsSession().Drive(driveInfo, EDriveE));On return, driveInfo.iType will have the type of drive E:. Itwill have the value of EMediaHardDisk if drive E: is the memorycard or hard disk.

If drive E: is not available, it will have the value ofEMediaNotPresent.Solution: You can use the RFile class to read binary data. There areseveral variants of the RFile::Read() method for different purposes.In general, there are two types: synchronous and asynchronous. For eachtype, there are variants to write the entire descriptor or with specificlength and/or from a specific index.The following example shows how to read the binary data from thefile:void CBinaryFileAppUi::ReadDesCFromFileL(RFs& aFs,const TDesC& aFileName, TDes8& aBuffer){RFile file;User::LeaveIfError(file.Open(aFs, aFileName, EFileRead));CleanupClosePushL(file);// Get the file size.TInt fileSize;User::LeaveIfError(file.Size(fileSize));// If the maximum length of the buffer is less than the file size,// it means we don’t have enough space.if (aBuffer.MaxLength() < fileSize){User::Leave(KErrOverflow);}User::LeaveIfError(file.Read(aBuffer, fileSize));CleanupStack::PopAndDestroy(&file); // file}Discussion: The ReadDesCFromFileL() method reads the contents ofa file, aFileName, into a buffer, aBuffer.

Note that aBuffer musthave enough space to hold the entire contents of the file.84SYMBIAN C++ RECIPESThe RFile::Open() method can return error codes such as KErrNotFound (-1) when the file cannot be found or KErrPathNotFound(-12) when the path cannot be found. For a complete list of error codes,please check \epoc32\include\e32err.h.The file size information is needed to read the file to the buffer. It isalso used to check whether the buffer has enough space to hold the data.Note that this function reads the whole contents of the file at once. Itis not recommended to do it this way if the file is large.

The applicationwill block at the RFile::Read() method. The user interface will notbe responsive during that period.Besides, this method creates a buffer that has the same size as the filesize. For a large file, you may end up in an out-of-memory situation.A better way of handling a large file is by creating an active object andusing the asynchronous overload of RFile::Read().Using the ReadDesCFromFileL() function and the WriteDesCToFileL() from the previous recipe, we can write a simple copyingprogram. Here is an example:RFs& fileServer = iCoeEnv->FsSession();// Create a new bufferRBuf8 buffer;User::LeaveIfError(buffer.CreateMax(KMaxBuffer));CleanupClosePushL(buffer);// Read from the file.// We have to make sure that the buffer has enough space,// otherwise it will panic.ReadDesCFromFileL(fileServer, KSourceFileName, buffer);// Write the buffer to a file.WriteDesCToFileL(fileServer, KDestFileName, buffer);// Delete the buffer.CleanupStack::PopAndDestroy(&buffer);You can do many interesting things by modifying the buffer afterreading but before writing.

For example:• Replace characters with some other characters, such as replace ‘<’with ‘<’.• Insert or delete some characters.• Encrypt or compress the buffer.FILE HANDLING85Tip: You can copy a file using a method called CFileMan::Copy().For example:CFileMan* fileMan = CFileMan::NewL(fileServer);CleanupStack::PushL(fileMan);fileMan->Copy(KOrgFileName, KNewFileName, CFileMan::EOverWrite);CleanupStack::PopAndDestroy(fileMan);4.1.1.4Read Text from a FileAmount of time required: 15 minutesLocation of example code: \Files\TextFileRequired library(s): efsrv.libRequired header file(s): f32file.hRequired platform security capability(s): NoneProblem: You want to read a text file.Solution: A text file is basically a file that has an EOL (End-Of-Line)delimiter that separates one line from another.

The delimiter that is commonly used in Symbian OS is the LF (0x0A) character, which is the sameas on a UNIX platform. Note that it is different from Windows, whichuses CR LF (0x0D 0x0A). On Symbian OS, a text file is usually stored inUnicode format.The class to read/write a text file is TFileText.

It is declared in thef32file.h header file and the library name is efsrv.lib.Before using TFileText, you have to open a file using RFilebecause the TFileText class does not have an Open() method.There are two basic methods in TTextFile; that is, Read() andWrite(). Both of them require a 16-bit descriptor parameter becauseSymbian OS stores text files in Unicode format.The following code shows how to read a text file:void CTextFileAppUi::ReadFromTextFileL(RFs& aFs,const TDesC& aFileName){// Open the file for reading.RFile file;User::LeaveIfError(file.Open(aFs, aFileName,EFileRead | EFileStreamText));CleanupClosePushL(file);// Create a new instance of TFileText that86SYMBIAN C++ RECIPES// points to file.TFileText fileText;fileText.Set(file);// Create a buffer to read the text file.TBuf<KMaxBuffer> buffer;// Loop to read the buffer.// It reads the buffer until err is KErrEof,// which means it reached the end of the file.TInt err = KErrNone;while (err != KErrEof){err = fileText.Read(buffer);// If the error code is other than KErrNone// or KErrEof, leave this function.if ((err != KErrNone) && (err != KErrEof)){User::Leave(err);}if (KErrNone == err){// Do something with the buffer.}}CleanupStack::PopAndDestroy(&file);}Discussion:Tip: You can use TFileText to read a Unicode file that has CRLF or LF as delimiter.

It is able to handle a file that contains BOM(Byte-Order Mark ) as well.Note the EFileStreamText flag, which indicates the opened filewill be used as a text file. The end of file is indicated by the return valueof TFileText::Read(), which is KErrEof.What may go wrong when you do this: Do not use TFileText toopen a file other than Unicode. You will get garbage characters iftrying to access non-Unicode files, such as ASCII files.4.1.2 Intermediate Recipes4.1.2.1Get the Path of a Private FolderAmount of time required: 15 minutesLocation of example code: \Files\FileSharingCreatorFILE HANDLING87Required library(s): efsrv.libRequired header file(s): f32file.hRequired platform security capability(s): NoneProblem: Data caging provides protection to some special folders.

One ofthem is the application’s private folder. It is located at \private\<SID>,where <SID> is the secure identifier of the application. This folder isnormally used by the application to store its own data, which cannotbe accessed by other processes. Since <SID> depends on the secureidentifier of the application, how do we get the path of the private folderat runtime?Solution: The RFs::PrivatePath() method returns the private pathin the format of ‘\private\<SID>’. For example, if the application hasa secure identifier which is 0xA1234567, then the private path will be‘\private\A1234567’ (without ‘0x’).Discussion: How do we add a filename to the path? For example, wewant to add ‘myfile.dat’ at the end of the private path.Furthermore, how do we add a drive letter that is the same as theapplication’s drive letter? For example, if the application is installedon the E: drive, we want to access the private folder located ate:\private\<SID>.Constructing a full filename can be done manually using descriptormethods, such as TDes::Insert() and TDes::Append().There is another way of constructing the filename, which is using theTParse class.

This class is usually used to construct a filename basedon its components. The construction is done with the method TParse::Set():IMPORT_C TInt Set(const TDesC& aName, const TDesC* aRelated,const TDesC* aDefault);The first parameter, aName, is the file specification to be parsed.The second parameter, aRelated, is the related specification ofaName.

Any missing component, such as a path or filename, in the firstparameter will be set to those in the second parameter. For example, ifthe first parameter contains the path only, you can set a drive letter usingthe second parameter. If there is no related specification, then set thisparameter to NULL.The third parameter is the default file specification. Like the secondparameter, if a component has no value in the first and second parameters,it will be assigned the value in the third parameter.Let’s take a look at a real example to see how it works:88SYMBIAN C++ RECIPES// Get the private path of the application.RBuf privatePath;privatePath.CreateL(KMaxFileName);CleanupClosePushL(privatePath);User::LeaveIfError(fs.PrivatePath(privatePath));// Add name and extension to the path._LIT(KNameAndExt, "example.txt");TParse parse;// "\private<SID>\example.txt"User::LeaveIfError(parse.Set(privatePath, 0, &KNameAndExt));The filename after Set() will be ‘\private\<SID>\example.txt’.Notice that the first parameter, privatePath, contains no filename.Since there are no name and extension in this path, after calling Set(),they are assigned according to KNameExt.The following code adds a drive letter to the private path:// Get the private path of the application.RBuf privatePath;privatePath.CreateL(KMaxFileName);CleanupClosePushL(privatePath);User::LeaveIfError(fileServer.PrivatePath(privatePath));// Add name and extension to the path._LIT(KNameAndExt, "c:example.txt");TParse parse;User::LeaveIfError(parse.Set(privatePath, 0, &KNameAndExt));Tip: When creating a package file for software installation, you canspecify ‘!:’ as the drive letter in the PKG file.

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

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

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

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