版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年新媒体数字项目合作计划书
- 2025关于出租汽车驾驶员劳动合同书范本
- 2025福建农业种植产销合同
- 2025版养老院隔音降噪施工及安全保障合同2篇
- 2025版中草药种植基地农产品溯源服务合同2篇
- 2025年度综合安防设备租赁合同范本3篇
- 2024年网站建设合同:企业网站的定制开发与运维
- 2025版驾校教练员学生满意度评价聘用协议3篇
- 2025版互联网数据中心运维托管合同3篇
- 2024年版详尽离婚合同财产分割范本版B版
- 湖南2025年湖南机电职业技术学院合同制教师招聘31人历年参考题库(频考版)含答案解析
- 2024年电子交易:电脑买卖合同
- 中国文化概论知识试题与答案版
- 期末复习提升测试(试题)(含答案)2024-2025学年四年级上册数学人教版
- 生和码头港口设施维护管理制度(3篇)
- 【MOOC】数字逻辑设计及应用-电子科技大学 中国大学慕课MOOC答案
- 铸牢中华民族共同体意识-形考任务3-国开(NMG)-参考资料
- 学术交流英语(学术写作)智慧树知到期末考试答案章节答案2024年哈尔滨工程大学
- TSEESA 010-2022 零碳园区创建与评价技术规范
- 无形资产评估习题与实训参考答案
- 注塑车间工作开展计划书
评论
0/150
提交评论