版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年新媒體數(shù)字項(xiàng)目合作計(jì)劃書
- 2025關(guān)于出租汽車駕駛員勞動合同書范本
- 2025福建農(nóng)業(yè)種植產(chǎn)銷合同
- 2025版養(yǎng)老院隔音降噪施工及安全保障合同2篇
- 2025版中草藥種植基地農(nóng)產(chǎn)品溯源服務(wù)合同2篇
- 2025年度綜合安防設(shè)備租賃合同范本3篇
- 2024年網(wǎng)站建設(shè)合同:企業(yè)網(wǎng)站的定制開發(fā)與運(yùn)維
- 2025版駕校教練員學(xué)生滿意度評價(jià)聘用協(xié)議3篇
- 2025版互聯(lián)網(wǎng)數(shù)據(jù)中心運(yùn)維托管合同3篇
- 2024年版詳盡離婚合同財(cái)產(chǎn)分割范本版B版
- 湖南2025年湖南機(jī)電職業(yè)技術(shù)學(xué)院合同制教師招聘31人歷年參考題庫(頻考版)含答案解析
- 2024年電子交易:電腦買賣合同
- 中國文化概論知識試題與答案版
- 期末復(fù)習(xí)提升測試(試題)(含答案)2024-2025學(xué)年四年級上冊數(shù)學(xué)人教版
- 生和碼頭港口設(shè)施維護(hù)管理制度(3篇)
- 【MOOC】數(shù)字邏輯設(shè)計(jì)及應(yīng)用-電子科技大學(xué) 中國大學(xué)慕課MOOC答案
- 鑄牢中華民族共同體意識-形考任務(wù)3-國開(NMG)-參考資料
- 學(xué)術(shù)交流英語(學(xué)術(shù)寫作)智慧樹知到期末考試答案章節(jié)答案2024年哈爾濱工程大學(xué)
- TSEESA 010-2022 零碳園區(qū)創(chuàng)建與評價(jià)技術(shù)規(guī)范
- 無形資產(chǎn)評估習(xí)題與實(shí)訓(xùn)參考答案
- 注塑車間工作開展計(jì)劃書
評論
0/150
提交評論