C语言程序设计课件英文Cprogramla_第1页
C语言程序设计课件英文Cprogramla_第2页
C语言程序设计课件英文Cprogramla_第3页
C语言程序设计课件英文Cprogramla_第4页
C语言程序设计课件英文Cprogramla_第5页
已阅读5页,还剩55页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ChapterSevenFileChapterSevenFile1Contents

Introduction1Open/closefile2Read/writefile

3

Checkthestateoftheopeningfile4Thelocationofthefilepointer54hapterSevenContentsIntroduction1Open/clo2Howtogetthedatawhilerunaprogram?Wherewilltheresultin?Howcaninputtheresultofaprogramtoanotherprogram?

Introduction

TheprocedureofClanguageEditLinkCreatetheprogramtextCompileCompileitsuccessfullyLinkittotheCfunctionlibrary

hapterSevenHowtogetthedatawhilerun3

Introductionprogram

formatoutputcharacteroutputstringoutputinitializationassignmentinputfromkeyboardmemorymemoryformatinputcharacterinputstringinputQuestionReaddatafromafileWritedatatoafilehapterSevenIntroductionprogramformato4

Introduction

Fileisthegatherofrelatedinformationsavedinmemorydevice(assistantmemory)

OSmanagessysteminfiles

Processingfilesmeansfileinput/outprocessing.Procedure1openfile2fileread/write3closefile.Interfaceinput/outdevicesaretreatedasfilesinC.Fileaccessingmethods:

1)BufferedI/O(orstreamI/O)2)UnbufferedI/O(orlow-levelI/O)hapterSevenIntroductionFileisth5

IntroductionBuffered(temporarystoragelocation)

We’lldiscussBufferedI/OinourlectureInbufferedI/O,---openacommunicationareainRAMDISkPROGRAMOutputfilebuffer

InputfilebufferTherearetwowaystodealwithfile:BinaryfileASCIIfilestreamhapterSevenIntroductionBuffered6

IntroductionstreamStreamistheabstractoffileusedtodealwithfile.TherearetwokindsofstreamsinC.ThecharacterisASCIIcode.oneASCIIcodeoccupiesonebyte,newline‘\n’isendofline.Afterread/writeacharacterfrom/toASCIIfile,thefpincreasesautomaticallytoguaranteetheread/writesequences.TextstreamBinarystreamStoringdatatodiskintheformthesameasinRAM.Example:10000Inbinaryfile,use2bytesInASCIIfile,use5byteshapterSevenIntroductionstreamStreamis7Open/closefileHowtomagangeafileinC?PointerOperationsopenfile(loadfile)operatefileusingfunctionsclosefile(removefilefrommemory)BDFACEAfilesystemcreatanewfiledeleteanoldoneread/write

accessafilebyitsnamemanagethememoryfileusedlimittheuser’srighthapterSevenOpen/closefileHowtomagange8Open/closefile

Filepointer,pointstoastructurethatcontainsinformationaboutthefile,suchasthelocationofabuffer,thecurrentcharacterpositioninthebuffer,whetherthefileisbeingreadorwritten,andwhethererrorsorendoffilehaveoccurred.Usersdon’tneedtoknowthedetails,becausethedefinitionsobtainedfrom<stdio.h>includeastructuredeclarationcalledFILE.

AboutfilepointerIamastudent.hapterSevenOpen/closefileFilepo9

2Thefunctionofopeningafile:FILE*fp;

uppercaseletters,otherwise,can’tberecognized,

definedtostandardstructure,key--word

#include<stdio.h>isnecessary

fopen(filename,*mode);stringchararraycharpointerpathsareallowed

1filespointer:openingafileusefunctionfopen()

readwriteappend……Open/closefilehapterSeven2Thefunctionofopeninga10Open/closefilefp=fopen(“file.txt”,“r”);openfile.txt,readinASCIIOpeningafilemeans….returnsafilepointerspecifytheoperationtobedone

definingafilenamefirst……pointstothefirstlocationoffilebuffer.r----readfile.txtwhichThereturnedvalueisassignedtoafilepointer.hapterSevenOpen/closefilefp=fopen(“fil11

Ifprocessissuccessful,thereturnedvalueisafilepointer.(address)FLIE*fp;Otherwise,returnNULLpointer.if((fp=fopen(“file.txt”“r”)==NULL)){printf(“can’topenfile\n”);exist(1);}Open/closefileSymbolExplanationrreadwwriteaappendtTextstreambBinarystream+Permitread/write

Iffopenfails,returnvalueiszero(NULLpointer)when:

1)fopenwantstoopenanonexistedfileforreading.2)readafilenotpermittedread.3)createafilebutdiskisfull.

4)disksectorisbad.hapterSevenIfprocessissuccessful,th123CloseafileCloseafileopened,argument&apointertofiletobeclosedinorderto1)releasefpand2)cleanupthebuffer.fclose(fp);Open/closefile

Openedfilemustbeclosedbeforeendingaprogram,otherwise,datamaybelost.hapterSeven3CloseafileCloseafileope13

Writesstringintofilepointedbystream

Fileread/writefgets(string,n,stream)

Readsastringofupton-1charactersfromstreamandplacesthemintostringfputs(string,stream)

1read/writefilefunctionsfgetc(fp),fputc(fp)

read/writeacharfrom/tofileread:c=fgetc(fp);readacharfromnamedfile.write:fputc(c,fp);writectonamedfile.Prototypeinstdio.hreturnEOF(-1)ifa)attheendoffile;b)detectinganerror;Usingfunctionfgets()andfputs()canrealizestringinput/ouputinfiles.hapterSevenWritesstringintofilepoi14

main(intargc,char*argv[]){intc;FILE*fpr,*fpd;if(argc!=3) {putchar('\007');puts("Usage:copyfile1,file2"); exit();} if((fpr=fopen(argv[1],"r"))==NULL) {printf("%c",'\007');printf("file%scan'topen\n",argv[1]); exit();} if((fpd=fopen(argv[2],"w"))==NULL) {printf("\files%scan'topen\n",argv[2]); exit();}while((c=fgetc(fpr))!=EOF)fputc(c,fpd);fclose(fpr);fclose(fpd);}Inputthreestrings(filename)Sourcefilenameobjectfilename

Thefunctionofthisprogramistocopyfile1tofile2hapterSevenmain(intargc,char15#include<stdio.h>main(){FILE*fp;charc1;fp=fopen(“file.dat”,”r”);

c1=fgetc(fp);putchar(c1);fclose(fp);}#include<stdio.h>main(){FILE*fp;charch=‘a’;fp=fopen(“file.dat”,”w”);fputc(ch,fp);fclose(fp);}Readthecharacterfromfile.dat

writecharacter‘a’tofile.dat.

Fileread/writefscanf(stream,format,arg,...)

Readsdatafromstreamusingformatconversionspecifierintoaddressspecifierdbyarg.fprintf(stream,format,arg,...)

Writesargintostreamusingformatconversionspecifier.hapterSeven#include<stdio.h>#include<stdi16main(){FILE*fp;char*c1=“TurboC”;charc2[10];fp=fopen(“file2.dat”,”w”);

fputs(c1,fp);

fclose(fp);fp=fopen(“file2.dat”,”r”);

fgets(c2,8,fp);printf(“%s\n”,c2);fclose(fp);}

Fileread/write

readastringfromdeterminedfile(fp),haveread7chars;Returnedvalue:normalthe1stlocationofthestring;errororendoffileNULLwriteastringtodeterminedfile(fp)Returnedvalue:normal:thenumberofchars;error:NULLhapterSevenmain()Fileread/writeread17main(){FILE*fp;char*c1=“TurboC”;charc2[10];fp=fopen(“file3.dat”,”w”);fprintf(fp,”%s”,c1);fclose(fp);fp=fopen(“file3.dat”,”r”);fscanf(fp,”%s”,c2);printf(“%s\n”,c2);fclose(fp);}

Fileread/writeItissimilartoprintf,addfp–filepointerItissimilartoscanf,addfp–filepointerhapterSevenmain()Fileread/writeItiss18main(){FILE*fp;charstr[81],filename[80];gets(filename);if((fp=fopen(filename,”w”))==NULL){printf(“cannotopenthisfile\n”);exit(0);}while(strlen(gets(str))>0){fputs(str,fp);fputs(“\n”,fp);}fclose(fp);}Inputseveralstrings,thensavethemtodiskCanyouuse“filename”here?Howmanystringsshouldyouinput??

Fileread/writehapterSevenmain()Inputseveralstrings,19freadreadsnitemsofsizelengthfromstreamintobuffer.

Fileread/write

fwrite()/fread()*Twostandardlibraryfunctionsareavailabletofacilitatethestorageofdataarraysinbinaryforms.Thesearefwrite()andfread().fwrite(buffer,size,n,stream);fread(buffer,size,n,stream);

buffer:apointertothestartofthebuffertobewrittenintostream.

n:itemsinthebufferoflengthsizeinbytes.hapterSevenfreadreadsnitemsofsizele20

whencomputerarestarted,3standardfilesareopenedautomatically,and3associatedfilepointersareprovided。Userneedn'twritestatementstoopenstandardfilesandafterprogramareexecuted,standardfilesautomaticallyclosed.2Interfaceinput/outdevicesstdinfileinputstdoutstandardoutputpointerstderrerror

exit(1):returntoos.Innormalexistexit(0):---normalexist.3Exitfunctionsprogramwillstoprightaway.

Fileread/writehapterSevenwhencomputerares21Thefile’sstateisnecessarywhenusinginput/outfunctions,especiallytestingtheendofafile.Thereareonecoupleofwaystotesttheendoffile1EOF

Whenreading/writingASCIIfile,EOFisusedtotestifthefilepointerpointstotheendoffile,ifso,thevalueofEOFis-1Can’tsuitforbinaryfile2functionfeof()

feof(filepointername)

Thereturnvalueisnonzeroattheendoffile,Otherwise,itisnottheendoffile.CheckthestateoftheopeningfilehapterSevenThefile’sstateisnecessary22while(feof(fp)==0)c=fgetc(fp);Checkthestateoftheopeningfilewhile((c=fgetc(fp)!=EOF))

putchar(c);Example:readcharactersfromafilehapterSevenwhile(feof(fp)==0)Checkthe23Thelocationofhefilepointer1rewind

rewind(filepointername)

Setsfilepointertostreamtobeginningoffile2fseek

Locatesfilepointerforstreamatoffsetbytesfromorigins

fseek(filepointername,offsets,origin)

Noreturnvalue

GenerallyitisUsedforbinaryfile0:thebegining1:currentposition2:theend

Thenumberofbytes+movebackwards-moveforwards

return:azeroifthepointerwasresetwithouterror.hapterSevenThelocationofhefilepointe243、Thecurrentposition

ftell(filepointername)

Returnscurrentpositionoffilepointedfromstream

Return1LmeansthereissomethingwrongThelocationofthefilepointerWhereisthecurrentpositionofthefilepointer?

0Beginningoffile1Currentpositionoffilepointer2Endoffile

fseek(filepointername,distance,origin)hapterSeven3、Thecurrentpositionftell25main(intargc,char*argv[]) {chars[80];inta; FILE*fp; if((fp=fopen("test","w"))==NULL) {printf("can'topenfile"); exit();} fscanf(stdin,"%s%d",s,&a);/*readfromkeyboard*/ fprintf(fp,"%s%d",s,a);/*writetofile*/ fclose(fp);if((fp=fopen("test","r"))==NULL) {printf("can'topenfile"); exit();}fscanf(fp,"%s%d",s,&a);/*readfromfile*/ fprintf(stdout,"%s%d",s,a);/*printonscreen*/ fclose(fp);}ThelocationofthefilepointerhapterSevenmain(intargc,char*argv[]26

/*WritinganarrayofdatausingfwriteFWRITE.C*/#include<stdio.h>main(){staticintbuffer[]={70,71,72,73,74,75,76,77,78,79,80,81,82,83};FILE*fp;inti;fp=fopen("testdata","w");fwrite((char*)buffer,2,14,fp);fclose(fp);}ThelocationofthefilepointerhapterSeven/*Writinganarrayofdata27

/*fread.c*/#include<stdio.h>main(){FILE*fp;staticintbuffer[14];inti;

fp=fopen("testdata","r");fread((char*)buffer,2,14,fp);fclose(fp);for(i=0;i<14;i++) printf("%d\n",buffer[i]);}ThelocationofthefilepointerhapterSeven/*fread.c*/Thelocation28

main(){staticcharbuffer[]="abcdefg";longpick;longoffset;charc; FILE*fp;fp=fopen("testdata","w");fwrite(buffer,1,7,fp); fclose(fp);fp=fopen("testdata","r");for(pick=3;pick<7;pick++){fseek(fp,pick,0);offset=ftell(fp);fscanf(fp,"%c",&c); printf("dataitematoffset%ldis%c\n",offset,c); }fclose(fp); }ThelocationofthefilepointerhapterSevenmain()Thelocationof29ThankYou!ThankYou!30ChapterSevenFileChapterSevenFile31Contents

Introduction1Open/closefile2Read/writefile

3

Checkthestateoftheopeningfile4Thelocationofthefilepointer54hapterSevenContentsIntroduction1Open/clo32Howtogetthedatawhilerunaprogram?Wherewilltheresultin?Howcaninputtheresultofaprogramtoanotherprogram?

Introduction

TheprocedureofClanguageEditLinkCreatetheprogramtextCompileCompileitsuccessfullyLinkittotheCfunctionlibrary

hapterSevenHowtogetthedatawhilerun33

Introductionprogram

formatoutputcharacteroutputstringoutputinitializationassignmentinputfromkeyboardmemorymemoryformatinputcharacterinputstringinputQuestionReaddatafromafileWritedatatoafilehapterSevenIntroductionprogramformato34

Introduction

Fileisthegatherofrelatedinformationsavedinmemorydevice(assistantmemory)

OSmanagessysteminfiles

Processingfilesmeansfileinput/outprocessing.Procedure1openfile2fileread/write3closefile.Interfaceinput/outdevicesaretreatedasfilesinC.Fileaccessingmethods:

1)BufferedI/O(orstreamI/O)2)UnbufferedI/O(orlow-levelI/O)hapterSevenIntroductionFileisth35

IntroductionBuffered(temporarystoragelocation)

We’lldiscussBufferedI/OinourlectureInbufferedI/O,---openacommunicationareainRAMDISkPROGRAMOutputfilebuffer

InputfilebufferTherearetwowaystodealwithfile:BinaryfileASCIIfilestreamhapterSevenIntroductionBuffered36

IntroductionstreamStreamistheabstractoffileusedtodealwithfile.TherearetwokindsofstreamsinC.ThecharacterisASCIIcode.oneASCIIcodeoccupiesonebyte,newline‘\n’isendofline.Afterread/writeacharacterfrom/toASCIIfile,thefpincreasesautomaticallytoguaranteetheread/writesequences.TextstreamBinarystreamStoringdatatodiskintheformthesameasinRAM.Example:10000Inbinaryfile,use2bytesInASCIIfile,use5byteshapterSevenIntroductionstreamStreamis37Open/closefileHowtomagangeafileinC?PointerOperationsopenfile(loadfile)operatefileusingfunctionsclosefile(removefilefrommemory)BDFACEAfilesystemcreatanewfiledeleteanoldoneread/write

accessafilebyitsnamemanagethememoryfileusedlimittheuser’srighthapterSevenOpen/closefileHowtomagange38Open/closefile

Filepointer,pointstoastructurethatcontainsinformationaboutthefile,suchasthelocationofabuffer,thecurrentcharacterpositioninthebuffer,whetherthefileisbeingreadorwritten,andwhethererrorsorendoffilehaveoccurred.Usersdon’tneedtoknowthedetails,becausethedefinitionsobtainedfrom<stdio.h>includeastructuredeclarationcalledFILE.

AboutfilepointerIamastudent.hapterSevenOpen/closefileFilepo39

2Thefunctionofopeningafile:FILE*fp;

uppercaseletters,otherwise,can’tberecognized,

definedtostandardstructure,key--word

#include<stdio.h>isnecessary

fopen(filename,*mode);stringchararraycharpointerpathsareallowed

1filespointer:openingafileusefunctionfopen()

readwriteappend……Open/closefilehapterSeven2Thefunctionofopeninga40Open/closefilefp=fopen(“file.txt”,“r”);openfile.txt,readinASCIIOpeningafilemeans….returnsafilepointerspecifytheoperationtobedone

definingafilenamefirst……pointstothefirstlocationoffilebuffer.r----readfile.txtwhichThereturnedvalueisassignedtoafilepointer.hapterSevenOpen/closefilefp=fopen(“fil41

Ifprocessissuccessful,thereturnedvalueisafilepointer.(address)FLIE*fp;Otherwise,returnNULLpointer.if((fp=fopen(“file.txt”“r”)==NULL)){printf(“can’topenfile\n”);exist(1);}Open/closefileSymbolExplanationrreadwwriteaappendtTextstreambBinarystream+Permitread/write

Iffopenfails,returnvalueiszero(NULLpointer)when:

1)fopenwantstoopenanonexistedfileforreading.2)readafilenotpermittedread.3)createafilebutdiskisfull.

4)disksectorisbad.hapterSevenIfprocessissuccessful,th423CloseafileCloseafileopened,argument&apointertofiletobeclosedinorderto1)releasefpand2)cleanupthebuffer.fclose(fp);Open/closefile

Openedfilemustbeclosedbeforeendingaprogram,otherwise,datamaybelost.hapterSeven3CloseafileCloseafileope43

Writesstringintofilepointedbystream

Fileread/writefgets(string,n,stream)

Readsastringofupton-1charactersfromstreamandplacesthemintostringfputs(string,stream)

1read/writefilefunctionsfgetc(fp),fputc(fp)

read/writeacharfrom/tofileread:c=fgetc(fp);readacharfromnamedfile.write:fputc(c,fp);writectonamedfile.Prototypeinstdio.hreturnEOF(-1)ifa)attheendoffile;b)detectinganerror;Usingfunctionfgets()andfputs()canrealizestringinput/ouputinfiles.hapterSevenWritesstringintofilepoi44

main(intargc,char*argv[]){intc;FILE*fpr,*fpd;if(argc!=3) {putchar('\007');puts("Usage:copyfile1,file2"); exit();} if((fpr=fopen(argv[1],"r"))==NULL) {printf("%c",'\007');printf("file%scan'topen\n",argv[1]); exit();} if((fpd=fopen(argv[2],"w"))==NULL) {printf("\files%scan'topen\n",argv[2]); exit();}while((c=fgetc(fpr))!=EOF)fputc(c,fpd);fclose(fpr);fclose(fpd);}Inputthreestrings(filename)Sourcefilenameobjectfilename

Thefunctionofthisprogramistocopyfile1tofile2hapterSevenmain(intargc,char45#include<stdio.h>main(){FILE*fp;charc1;fp=fopen(“file.dat”,”r”);

c1=fgetc(fp);putchar(c1);fclose(fp);}#include<stdio.h>main(){FILE*fp;charch=‘a’;fp=fopen(“file.dat”,”w”);fputc(ch,fp);fclose(fp);}Readthecharacterfromfile.dat

writecharacter‘a’tofile.dat.

Fileread/writefscanf(stream,format,arg,...)

Readsdatafromstreamusingformatconversionspecifierintoaddressspecifierdbyarg.fprintf(stream,format,arg,...)

Writesargintostreamusingformatconversionspecifier.hapterSeven#include<stdio.h>#include<stdi46main(){FILE*fp;char*c1=“TurboC”;charc2[10];fp=fopen(“file2.dat”,”w”);

fputs(c1,fp);

fclose(fp);fp=fopen(“file2.dat”,”r”);

fgets(c2,8,fp);printf(“%s\n”,c2);fclose(fp);}

Fileread/write

readastringfromdeterminedfile(fp),haveread7chars;Returnedvalue:normalthe1stlocationofthestring;errororendoffileNULLwriteastringtodeterminedfile(fp)Returnedvalue:normal:thenumberofchars;error:NULLhapterSevenmain()Fileread/writeread47main(){FILE*fp;char*c1=“TurboC”;charc2[10];fp=fopen(“file3.dat”,”w”);fprintf(fp,”%s”,c1);fclose(fp);fp=fopen(“file3.dat”,”r”);fscanf(fp,”%s”,c2);printf(“%s\n”,c2);fclose(fp);}

Fileread/writeItissimilartoprintf,addfp–filepointerItissimilartoscanf,addfp–filepointerhapterSevenmain()Fileread/writeItiss48main(){FILE*fp;charstr[81],filename[80];gets(filename);if((fp=fopen(filename,”w”))==NULL){printf(“cannotopenthisfile\n”);exit(0);}while(strlen(gets(str))>0){fputs(str,fp);fputs(“\n”,fp);}fclose(fp);}Inputseveralstrings,thensavethemtodiskCanyouuse“filename”here?Howmanystringsshouldyouinput??

Fileread/writehapterSevenmain()Inputseveralstrings,49freadreadsnitemsofsizelengthfromstreamintobuffer.

Fileread/write

fwrite()/fread()*Twostandardlibraryfunctionsareavailabletofacilitatethestorageofdataarraysinbinaryforms.Thesearefwrite()andfread().fwrite(buffer,size,n,stream);fread(buffer,size,n,stream);

buffer:apointertothestartofthebuffertobewrittenintostream.

n:itemsinthebufferoflengthsizeinbytes.hapterSevenfreadreadsnitemsofsizele50

whencomputerarestarted,3standardfilesareopenedautomatically,and3associatedfilepointersareprovided。Userneedn'twritestatementstoopenstandardfilesandafterprogramareexecuted,standardfilesautomaticallyclosed.2Interfaceinput/outdevicesstdinfileinputstdoutstandardoutputpointerstderrerror

exit(1):returntoos.Innormalexistexit(0):---normalexist.3Exitfunctionsprogramwillstoprightaway.

Fileread/writehapterSevenwhencomputerares51Thefile’sstateisnecessarywhenusinginput/outfunctions,especiallytestingtheendofafile.Thereareonecoupleofwaystotesttheendoffile1EOF

Whenreading/writingASCIIfile,EOFisusedtotestifthefilepointerpointstotheendoffile,ifso,thevalueofEOFis-1Can’tsuitforbinaryfile2functionfeof()

feof(filepointername)

Thereturnvalueisnonzeroattheendoffile,Otherwise,itisnottheendoffile.CheckthestateoftheopeningfilehapterSevenThefile’sstateisnecessary52while(feof(fp)==0)c=fgetc(fp);Checkthestateoftheopeningfilewhile((c=fgetc(fp)!=EOF))

putchar(c);Example:readcharactersfromafilehapterSevenwhile(feof(fp)==0)Checkthe53Thelocationofhefilepointer1rewind

rewind(filepointername)

Setsfilepointertostreamtobeginningoffile2fseek

Locatesfilepointerforstreamatoffsetbytesfromorigins

fseek(filepointername,offsets,origin)

Noreturnvalue

GenerallyitisUsedforbinaryfile0:thebegining1:currentposition2:theend

Thenumberofbytes+movebackwards-moveforwards

return:azeroifthepointerwasreset

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论