




已阅读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版大院租赁合同范本与租赁物质量验收及退租标准
- 二零二五年度城市综合体店面租赁合同
- 银行资本相关课件
- 银行网点绩效管理课件
- 旅行社工作年终总结
- 医院年度新闻宣传工作总结模版
- 铅笔笔芯安全课件下载
- 中国刺绣服装行业市场发展现状及前景趋势与投资分析研究报告(2024-2030)
- 2025年锯材项目投资分析及可行性报告
- 关爱老人的活动总结
- 餐饮食堂食品安全法培训
- 2025建筑工程土石方挖掘与运输合同范本
- 2025年智慧农业技术考试试卷及答案
- 质量控制与质量保证课件
- 分布式光伏发电项目可行性研究报告
- 带状疱疹及带状疱疹后神经痛课件
- 子女教育金理财保险
- 山东省日照市各县区乡镇行政村村庄村名居民村民委员会明细及行政区划代码
- 新高考背景下2023届高三化学一轮复习备考策略讲座
- 高校助学贷款结清凭证
- 英语阅读教学【讲座课件】
评论
0/150
提交评论