




版權(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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 財(cái)務(wù)管理b卷試題及答案
- 2019-2025年消防設(shè)施操作員之消防設(shè)備高級技能考前沖刺模擬試卷A卷含答案
- 2019-2025年消防設(shè)施操作員之消防設(shè)備中級技能考試題庫
- 工程熱力學(xué)應(yīng)用測試及答案
- 農(nóng)業(yè)現(xiàn)代化種植標(biāo)準(zhǔn)化體系建設(shè)方案
- 客戶咨詢與需求記錄表
- 傳統(tǒng)文化在初中英語課中深度融入教案
- 儀器設(shè)備使用說明及維護(hù)保養(yǎng)指導(dǎo)書
- 美容美發(fā)服務(wù)安全責(zé)任協(xié)議書
- 《小學(xué)數(shù)學(xué)幾何圖形識別與性質(zhì)理解教學(xué)方案》
- 臺區(qū)智能融合終端通用技術(shù)規(guī)范2022
- 備用圖標(biāo)庫(以便表達(dá)不同主題)
- 教科版二年級科學(xué)上冊《書的歷史》教案
- 中轉(zhuǎn)倉庫管理制度
- 新規(guī)重慶市律師服務(wù)收費(fèi)指導(dǎo)標(biāo)準(zhǔn)出臺
- 工程部SOP(標(biāo)準(zhǔn)操作手冊)
- 人教版(2019)高中英語必修第二冊:Unit5Music單元測試(含答案與解析)
- 21級全新版大學(xué)進(jìn)階英語2 國際班 教案
- 圖解心經(jīng)心得整理分享PPT課件
- 武漢市第五醫(yī)院重離子治療中心項(xiàng)目可行性研究報(bào)告
- (完整版)學(xué)生課堂學(xué)習(xí)自我評價(jià)表
評論
0/150
提交評論