![C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 10 LinkedList_第1頁](http://file4.renrendoc.com/view11/M01/37/09/wKhkGWWxKeiAIzhBAABkMBX_9Aw117.jpg)
![C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 10 LinkedList_第2頁](http://file4.renrendoc.com/view11/M01/37/09/wKhkGWWxKeiAIzhBAABkMBX_9Aw1172.jpg)
![C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 10 LinkedList_第3頁](http://file4.renrendoc.com/view11/M01/37/09/wKhkGWWxKeiAIzhBAABkMBX_9Aw1173.jpg)
![C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 10 LinkedList_第4頁](http://file4.renrendoc.com/view11/M01/37/09/wKhkGWWxKeiAIzhBAABkMBX_9Aw1174.jpg)
![C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 10 LinkedList_第5頁](http://file4.renrendoc.com/view11/M01/37/09/wKhkGWWxKeiAIzhBAABkMBX_9Aw1175.jpg)
版權(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)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024屆河北省高職單招數(shù)學(xué)等差專項(xiàng)練習(xí)
- 2024-2025學(xué)年廣東省平遠(yuǎn)縣實(shí)驗(yàn)中學(xué)高三上學(xué)期第二段考?xì)v史試卷
- 2025年預(yù)付商業(yè)裝修工程合同范文樣式
- 2025年光伏組件市場策劃購銷合同
- 2025年熱量表項(xiàng)目提案報(bào)告模板
- 2025年專業(yè)紅娘服務(wù)合同文本
- 2025年策劃版集體土地征收補(bǔ)償協(xié)議范本
- 2025年住宅翻新管理協(xié)議書
- 2025年健身導(dǎo)師聘請合同模板
- 2025年自動酸雨采樣器及測定儀項(xiàng)目規(guī)劃申請報(bào)告模范
- 鋼樓梯計(jì)算(自動版)
- 耳鼻咽喉科臨床診療指南
- 第二部分-3 植物纖維化學(xué)部分-纖維素
- 民法原理與實(shí)務(wù)課程教學(xué)大綱
- 2019北師大版高中英語選擇性必修四單詞表
- 園藝產(chǎn)品的品質(zhì)講義
- 鋼筋混凝土框架結(jié)構(gòu)工程監(jiān)理的質(zhì)量控制
- 桃花節(jié)活動方案
- 社區(qū)醫(yī)院建設(shè)標(biāo)準(zhǔn)
- 變更戶主情況登記表
- 個人所得稅稅率表【自動提取稅率計(jì)算】
評論
0/150
提交評論