已阅读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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年嘉兴市南湖区人民医院招聘事业单位工作人员3人笔试考试备考题库及答案解析
- 2025年烟台市莱山区辅警招聘考试题库附答案解析
- 2026 年高职健身指导与管理(健身计划制定)试题及答案
- 2025年大足县保安员招聘考试题库附答案解析
- 单位主要负责人考试历年真题集锦4套合1(附带答案)卷40
- 行政办事技师试题及答案
- 2025辽宁省地矿集团校园招聘61人笔试历年参考题库附带答案详解
- 2025江西九江市德安县博河物业有限公司招聘1人笔试历年参考题库附带答案详解
- 2025年贵州成黔集团铝产业精深加工板块招聘笔试历年参考题库附带答案详解
- 2025国家电投集团中国电力招聘33人笔试历年参考题库附带答案详解
- 竞聘库房管理岗位
- 石灰岩矿开采及综合利用项目施工方案
- 2025年安全信息考试试题及答案
- 2025标准网签购房合同范本下载
- 2025 年氢能工业与应用研究报告
- 云南人力资源开发有限责任公司招聘笔试题库2025
- 人教版八年级上册生物第五单元第一章综合实践项目 设计并制作生态瓶
- 2025河南城发环保能源有限公司下属项目公司校园招聘110人笔试考试参考题库及答案解析
- 2025全国医疗应急能力培训系列课程参考答案
- 理性看待分数用心守护成长+2025-2026学年高二上学期期中家长会主题班会
- 企业货款清欠流程及管理措施
评论
0/150
提交评论