File_Processing(英文版).ppt_第1页
File_Processing(英文版).ppt_第2页
File_Processing(英文版).ppt_第3页
File_Processing(英文版).ppt_第4页
File_Processing(英文版).ppt_第5页
已阅读5页,还剩39页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ProgramminginC Lecture8 CFileProcessing Outline DataandDataFilesFilesandStreamsSequentialAccessFilesRandomAccessFiles DataandDataFiles DataFilescanbecreated updated andprocessedbyCprogramsusedforpermanentstorage 持久存储 oflargeamountsofdataStorageofdatainvariablesandarraysisonlytemporary 临时的 Allsuchdataarelostwhentheprogramterminates TheDataHierarchy 1 Bit smallestdataitemValueof0or1Byte 8bitsUsedtostoreacharacter Decimaldigits letters andspecialsymbolsField groupofcharactersconveyingmeaningExample yourname TheDataHierarchy 2 Record groupofrelatedfieldsRepresentedbyastruct oraclassinC Example Inapayrollsystem arecordforaparticularemployeethatcontainedhis heridentificationnumber possiblerecordkey name address etc File groupofrelatedrecordsExample payrollfileDatabase groupofrelatedfiles TheDataHierarchy 3 TheDataHierarchy 4 Example Fig 11 1 Outline DataandDataFilesFilesandStreamsSequentialAccessFilesRandomAccessFiles FilesandStreams CviewseachfileasasequenceofbytesFileendswiththeend of file EOF markerOr fileendsataspecifiedbyte EOFandfeof aredefinedin Example while c getchar EOF if feof stdin EOFKeyCombinations DifferentfordifferentOS FilesandStreams AStreamiscreatedwhenafileisopenedProvidecommunicationchannel 通信渠道 betweenfilesandprogramsOpeningafilereturnsapointertoaFILEstructureExamplefilepointers stdin standardinput keyboard stdout standardoutput screen stderr standarderror screen FILEstructure TheprogrammerneednotknowthespecificsoftheFILEstructuretousefiles Filedescriptor 文件描述符 Indexintooperatingsystem OS arraycalledtheopenfiletableFileControlBlock FCB Foundineveryarrayelement systemusesittoadministerthefile RefertoFig 11 5onpage437 Outline DataandDataFilesFilesandStreamsSequentialAccessFilesRandomAccessFiles Read WriteFunctions 1 includeintfgetc FILE stream ReadonecharacterfromafileTakeaFILEpointerasanargumentfgetc stdin equivalenttogetchar intfputc intc FILE stream WriteonecharactertoafileTakeaFILEpointerandacharactertobewrittenasargumentsfputc a stdout equivalenttoputchar a Read Writefunctions 2 char fgets char s intn FILE stream Readsalinefromafileintfputs char s FILE stream Writesalinetoafilefscanf fprintfintfscanf FILE stream constchar format intfprintf FILE stream constchar format Fileprocessingequivalentsofscanfandprintf FrameworkforCreateasequentialfile seeFig 11 3onP433fordetails includeintmain FILE cfPtr cfPtr clients datfilepointer if cfPtr fopen clients dat w NULL printf Filecouldnotbeopened n else scanf d s lf CreatingaSequentialAccessFile FILE cfPtr DeclaresaFILEpointercalledcfPtrcfPtr fopen clients dat w FunctionfopenreturnsaFILEpointertofilespecifiedTakestwoarguments thefiletobeopenedandtheopenmodeIfopenfails NULLisreturned CreatingaSequentialAccessFile fprintfUsedtoprinttoafileLikeprintf exceptfirstargumentisaFILEpointer pointertothefileyouwanttoprint feof FILEpointer Returnstrueifend of file EOF indicator nomoredatatoprocess issetforthespecifiedfilefclose FILEpointer ClosesspecifiedfilePerformedautomaticallywhenprogramendsGoodpractice closefilesexplicitly FileOpenModes SequentialAccessFiles Alsocalledtextfile 文本文件 EachbytestoresanASCIIcode representingacharacterFormatofdatainatextfileisnotidenticalwithitsformatstoredinmemory E g 7 14areintsoccupying4byteseachinternally buttheyareofdifferentsize 1and3bytes astextinafile Fig 11 7 readingandprintingasequentialfile includeintmain FILE cfPtr cfPtr clients datfilepointer if cfPtr fopen clients dat r NULL printf Filecouldnotbeopened n else printf 10s 13s s n Account Name Balance fscanf cfPtr d s lf ReadingDatafromaSequentialAccessFile CreateaFILEpointer linkittothefiletoreadcfPtr fopen clients dat r UsefscanftoreadfromthefileLikescanf exceptfirstargumentisaFILEpointerfscanf cfPtr d s f Datareadfrombeginningtoend ReadingDatafromaSequentialAccessFile FilepositionpointerIndicatesnumberofnextbytetoberead writtenNotreallyapointer butanintegervalue specifiesbytelocation Alsocalledbyteoffsetrewind cfPtr Repositionsfilepositionpointertobeginningoffile byte0 ReadingDatafromaSequentialAccessFile FieldscanvaryinsizeDifferentrepresentationinfilesandscreenthaninternalrepresentation1 34 890areallints buthavedifferentsizesinfileCannotbemodifiedwithouttheriskofdestroyingotherdata 修改文件内容时有可能破坏不该破坏的数据 ReadingDatafromaSequentialAccessFile Outline DataandDataFilesFilesandStreamsSequentialAccessFilesRandomAccessFiles RandomAccessFiles Alsocalledbinaryfiles 二进制文件 Formatofdatainabinaryfileisidentical 同样的 withitsformatstoredinmemory bytedoesn tnecessarilyrepresentcharacter groupsofbytesmightrepresentothertypesofdata suchasintegersandfloating pointnumbersRecordsinbinaryfileshaveidenticallength RandomAccessFiles Example 12345 ASCIIcodesof5characters Aninteger RandomAccessFiles AccessindividualrecordswithoutsearchingthroughotherrecordsInstantaccesstorecordsinafile 对文件记录的随机访问 DatacanbeinsertedwithoutdestroyingotherdataDatapreviouslystoredcanbeupdatedordeletedwithoutoverwriting RandomAccessFiles C viewofarandom accessfile Fig 11 11 Creatingarandomlyaccessedfilesequentially withemptystructs includestructclientData intacctNum charlastName 15 charfirstName 10 doublebalance intmain inti structclientDatablankClient 0 0 0 FILE cfPtr if cfPtr fopen credit dat w NULL printf Filecouldnotbeopened n else for i 1 i 100 i fwrite UnformattedFileI OFunctions fwrite Transferbytesfromalocationinmemorytoafilesize tfwrite constvoid buffer size tsize size tnmemb FILE fp fread Transferbytesfromafiletoalocationinmemorysize tfread void buffer size tsize size tnmemb FILE fp UnformattedFileI OFunctions Example fwrite Number anintegervariable number locationtotransferbytesfromsizeof int numberofbytestotransfer1 forarrays numberofelementstotransferInthiscase oneelement ofanarray i e onenumberisbeingtransferredmyPtr Filetotransfertofreadsimilar UnformattedFileI OFunctions fwrite Towriteadatablockwithdesignatedsizetoafilesizeof returnthesizeinbytesoftheobjectinparenthesesTowriteseveralarrayelementsPointertoarrayasfirstargumentNumberofelementstowriteasthirdargument Fig 11 12 Writingtoarandomaccessfile intmain FILE cfPtr structclientDataclient 0 0 0 if cfPtr fopen credit dat r NULL printf Filecouldnotbeopened n else while client acctNum 0 printf Enterlastname firstname balance n fscanf stdin s s lf client lastName client firstName WritingDataRandomlytoaRandomAccessFile intfseek FILE stream longintoffset intwhence Setthefilepositionpointertoaspecificpositionstream pointertofileoffset filepositionpointer 0isfirstlocation whence specifieswhereinfilewearereadingfromSEEK SET seekstartsatbeginningoffileSEEK CUR seekstartsatcurrentlocationinfileSEEK END seekstartsatendoffileSucceed return0 WritingDataRandomlytoaRandomAccessFile Fig 11 15Readingarandomaccessfilesequentially intmain FILE cfPtr structclientDataclient if cfPtr fopen credit dat r NULL printf Filecouldnotbeopened n else printf 6s 16s 11s 10s n Acct LastName FirstName Balance while fread ReadingDataSequentiallyfromaRandomAccessFile intfread ReadsaspecifiednumberofbytesfromafileintomemoryCanreadseveralfixed sizearrayelementsProvidepointertoarrayIndicatenumberofelementstoreadNumberspecifiedinthe3rdargumentreturnthenumberofitemssuccessfullyr

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论