




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter10Cfiles10.1Streams10.2FileOperations10.3CharacterI/O10.4LineI/O10.5FormattedI/O10.6BlockI/O10.7FilePositioning10.1StreamsWhyfilesareneeded?Storinginafilewillpreserveyourdataeveniftheprogramterminates.youcaneasilyaccessthecontentsofthefileusingafewcommandsinC.Youcaneasilymoveyourdatafromonecomputertoanotherwithoutanychanges.10.1StreamsInC,thetermstreammeansanysourceofinputoranydestinationforoutput.Manysmallprogramsobtainalltheirinputfromonestream(thekeyboard)andwritealltheiroutputtoanotherstream(thescreen).Largerprogramsmayneedadditionalstreams.Streamsoftenrepresentfilesstoredonvariousmedia.However,theycouldjustaseasilybeassociatedwithdevicessuchasnetworkportsandprinters.4StreamsStandardStreams<stdio.h>
providesthreestandardstreams: FilePointer Stream DefaultMeaning
stdin
Standardinput Keyboard
stdout
Standardoutput Screen
stderr Standarderror Screen 5
WorkingwithfilesFilePointersAccessingastreamisdonethroughafilepointer,whichhastypeFILE
*.TheFILEtypeisdeclaredin<stdio.h>.Whenworkingwithfiles,youneedtodeclareapointeroftypefile.Thisdeclarationisneededforcommunicationbetweenthefileandtheprogram.
FILE*fp;6
TypesofFiles:TextfilesandBinaryfiles1.TextfilesTextfilesarethenormal
.txt
files.
In
textfile,the
text
andcharactersarestoredonecharacterperbyte.Forexample,theintegervalue12345occupy5bytesin
textfile.72.Binaryfiles
Insteadofstoringdatainplaintext,theystoreitinthebinaryform(0'sand1's).In
binaryfile,theintegervalue12345willoccupy4bytes.StreamsTextFilesversusBinaryFiles
Textfilesaredividedintolines.
Textfilesmaycontainaspecial“end-of-file”marker.Inabinaryfile,therearenoend-of-lineorend-of-filemarkers;allbytesaretreatedequally.Programsthatreadfromafileorwritetoafilemusttakeintoaccountwhetherit’stextorbinary.Whenwecan’tsayforsurewhetherafileistextorbinary,it’ssafertoassumethatit’sbinary.910.2FileOperationsFileOperationsInC,youcanperformfourmajoroperationsonfiles,eithertextorbinary:OpeningafileClosingafileReadingfromandwritinginformationtoafileMovingtoaspecificlocationinafile1010.2FileOperationsPrototypeforfopen: FILE*fopen(constchar*filename,constchar*mode);filenameisthenameofthefiletobeopened.Thisargumentmayincludeinformationaboutthefile’slocation,suchasadrivespecifierorpath.modeisa“modestring”thatspecifieswhatoperationsweintendtoperformonthefile.FileOperations
InWindows,becarefulwhenthefilenameinacalloffopenincludesthe\character.Thecallfopen("c:\homework\t1.txt","r") willfail,because\tistreatedasacharacterescape.Onewaytoavoidtheproblemistouse\\insteadof\: fopen("c:\\homework\\t1.txt","r")Analternativeistousethe/characterinsteadof\:
fopen("c:/homework/t1.txt","r")12FileOperations
fopenreturnsafilepointerthattheprogramcan(andusuallywill)saveinavariable: fp=fopen("t1.txt","r");//openst1.txtinthecurrentpathforreadingWhenitcan’topenafile,fopenreturnsanullpointer.13FileOperationsModesForopeningafile,fopenfunctionisusedwiththerequiredaccessmodes.Someofthecommonlyusedfileaccessmodesarementionedbelow.
14TextfileBinaryfileMeaningDuringInexistenceoffilerrbOpenforreading.Ifthefiledoesnotexist,fopen()returnsNULL.wwbOpenforwriting.Ifthefileexists,itscontentsareoverwritten.
Ifthefiledoesnotexist,itwillbecreated.aabOpenforappend.
Dataisaddedtotheendofthefile.Ifthefiledoesnotexist,itwillbecreated.r+rb+orr+bOpenforbothreadingandwriting.Ifthefiledoesnotexist,fopen()returnsNULL.w+wb+orw+bOpenforbothreadingandwriting.Ifthefileexists,itscontentsareoverwritten.
Ifthefiledoesnotexist,itwillbecreated.a+ab+ora+bOpenforbothreadingandappendingIfthefiledoesnotexist,itwillbecreated.FILE*fp1,*fp2;//Declarefilepointers
fp1=fopen("IN.TXT","r");//OpensatextfileIN.TXTinthecurrentpathforreadingfp2=fopen("OUT.DAT","wb");//CreatesanewbinaryfileOUT.DATinthecurrentpathforwritingIt’snotunusualtoseethecalloffopencombinedwiththedeclarationoffp: FILE*fp=fopen(“a.txt”,"r");FILE*fp;fp=fopen(“a.txt”,"r");TestNULL: if((fp=fopen(“a.txt”,"r"))!=NULL)…
FileOperationsClosingaFileThefclosefunctionallowsaprogramtocloseafilethatit’snolongerusing.Theargumenttofclosemustbeafilepointerobtainedfromacalloffopenorfreopen.Example:fclose(fp);
17Example:
ProgramtoOpenaFile,AndClosetheFile
#include<stdio.h>intmain(){
FILE*fp;//Declareafilepointer
fp=fopen(“a.txt",“r");//Openthefileusing“r"mode
if(fp==NULL)printf(“Error.\n");//CheckifthisfilePointerisnull
elseprintf("Thefileisnowopened.\n");
fclose(fp);//Closingthefileusingfclose()
return0;
}DetectingEnd-of-FileandErrorConditions
Cprovides
feof()
whichreturnsnon-zerovalueonlyifendoffilehasreached,otherwiseitreturns0.Syntax
intfeof(FILE*stream);while(!feof(fp)){//testiftheendoffilehasreached
…//ifnot,readorwritethefile}19Thecallferror()returnsanonzerovalueiftheerrorindicatorisset.syntaxintferror(FILE*stream);Example:ferror(fp);Clearerr()clearsboththeend-of-fileanderrorindicators.syntaxvoidclearerr(FILE*stream);clearerr(fp); /*clearseofanderrorindicatorsforfp*/10.3CharacterI/OOutputFunctions
fputcwritesacharactertoanarbitrarystream fputc(ch,fp);/*writeschtofp*/InputFunctions
fgetcreadsacharacterfromanarbitrarystream
ch=fgetc(fp);21#include<stdio.h>intmain(){FILE*fp;fp=fopen("a.txt","w");//openthe
file
fputc('x',fp);//write
single
character
”x”into
file
fclose(fp);//close
file
return0;}
Oneofthemostcommonusesoffgetcistoreadcharactersfromafile.Atypicalwhileloopforthatpurpose: while((ch=fgetc(fp))!=EOF){ … }
EOF
indicates"endoffile".
23#include<stdio.h>intmain(){FILE*fp;charc;fp=fopen("a.txt","r");//openthefilewhile((c=fgetc(fp))!=EOF){//Takinginputsinglecharacteratatimeprintf("%c",c);}fclose(fp);return0;}10.4LineI/OOutputFunctionsfputs
writesalineofcharactersintofile.int
fputs(const
char
*s,
FILE
*stream)
fputs("Hi!",fp);
/*writestofp*/
InputFunctions
fgetsreadsalineofcharactersfromfile.char*
fgets(char
*str,
int
n,
FILE
*stream)
charstr[100];fgets(str,99,fp);25#include<stdio.h>intmain(){FILE*fp;fp=fopen("a.txt","w");//openthefilefputs("hello",fp);//write”hello”into
file
fclose(fp);//close
file
return0;}#include<stdio.h>intmain(){FILE*fp;chartext[100];fp=fopen("a.txt","r");//openthefilefgets(text,99,fp);
//readfromfile
puts(text);fclose(fp);//close
file
return0;}10.5FormattedI/OThefprintf
functionwriteavariablenumberofdataitemstoanoutputstream,usingaformatstringtocontroltheappearanceoftheoutput.Theprototypesforthefunctionsendwiththe...symbol(anellipsis),whichindicatesavariablenumberofadditionalarguments: intfprintf(FILE*restrictstream,constchar*restrictformat,...);
fprintf(fp,“%d\n",a);
/*writestofp*/FormattedI/O
fscanf
readdataitemsfromaninputstream,usingaformatstringtoindicatethelayoutoftheinput. fscanf(fp,"%d%d",&a,&b);
/*readsfromfp*/
2910.6BlockI/OThefreadandfwritefunctionsallowaprogramtoreadandwritelargeblocksofdatainasinglestep.freadandfwriteareusedprimarilywithbinarystreams30BlockI/Ofwriteisdesignedtocopyanarrayfrommemorytoastream.size_tfwrite(constvoid*buffer,size_tsize,size_tcount,FILE*stream);Argumentsinacalloffwrite:AddressofarraySizeofeacharrayelement(inbytes)NumberofelementstowriteFilepointerAcalloffwritethatwritesastructurevariablestoafile:
fwrite(&s,sizeof(s),1,fp);
BlockI/Ofreadwillreaddatafromthegiven
stream
intothearraypointedto.size_tfread(void*buffer,size_tsize,size_tcount,FILE*stream);Parametersbuffer
−Thisisthepointertoablockofmemorysize
−Thisisthesizeinbytesofeachelementtoberead.count
−Thisisthenumberofelements,eachonewithasizeof
size
bytes.stream
−ThisisthepointertoaFILEobjectthatspecifiesaninputstream.Acalloffreadthatreadsthecontentsofafileintothearray:
fread(array,sizeof(int),100,fp);3210.7FilePositioningEverystreamhasanassociatedfileposition.
Whenafileisopened,thefilepositionissetatthebeginningofthefile.In“append”mode,theinitialfilepositionmaybeatthebeginningorend,dependingontheimplementation.Whenareadorwriteoperationisperformed,thefilepositionadvancesautomatically,providingsequentialaccesstodata.33FilePositioningAlthoughsequentialaccessisfineformanyapplications,someprogramsneedtheabilitytojumparoundwithinafile.Ifafilecontainsaseriesofrecords,wemightwantt
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 青岛市L区智慧养老服务问题与对策研究
- 转动型双阶摩擦阻尼器力学性能研究
- 肝胆疾病超声诊断
- 幼儿园大班健康礼仪下册
- 呼吸机的使用及护理
- 创新养老服务模式与老年健康管理实践
- 《机械设计基础》课件-第12章 机械传动设计
- 学生心理疏通和辅导培训会
- 预防儿童流感课件
- 感染科主要诊断
- 2025年校长职级考试题及答案
- 国家能源集团采购管理规定及实施办法知识试卷
- 2023-2024学年四川省成都市高新区八年级(下)期末数学试卷
- 2025年广西继续教育公需科目考试试题和答案
- 2024年广州市南沙区社区专职招聘考试真题
- 山东医药技师学院招聘笔试真题2024
- (高清版)DB13(J)∕T 8556-2023 建设工程消耗量标准及计算规则(园林绿化工程)
- JJF 1334-2012混凝土裂缝宽度及深度测量仪校准规范
- GB/T 3003-2017耐火纤维及制品
- GB/T 1094.1-2013电力变压器第1部分:总则
- 经济责任审计报告
评论
0/150
提交评论