You are on page 1of 4

1/29/2017 VisualBasicCh.

10Notes,page1

CIS230,VisualBasic

Ch.10Notes,page1

Objective#1:Createdatafiles.

Manyprogrammingapplicationsrequiredatatobestoredandupdatedbetweenexecutions.Tostorethisdata,weusedatafiles.Often,theyare
called"externalfiles"sincetheydonotcontainexecutablecodethatmakestheprogramrun.Datafilescontaininformationthatismadeupof
recordswhichcanbeaccessed(i.e.read)ormodified(i.e.writtento)byVBprograms.Generally,threetypesofdatafilesareusedinVB:
sequential,randomaccess,andbinary.Wewillnotstudybinaryfilesinthiscourse.
Tocreateadatafile,youcanuseanytexteditingorwordprocessingapplication.Carefullytypethenecessarydataandsavethefilewitha.txt
or.datextensionsothatotherapplicationsandpeoplewillrecognizethefileasadatatextfile.Often,NotePadorWordPadisusedtocreatea
datafile.TheseprogramscanusuallybefoundintheAccessoriesfolderonanyWindowsPC.
AfilemustbeopenedfromwithinVisualBasicbeforeitiscanbeusedbytheprograminanyway.ToopenafileusetheOpenstatement.The
generalformoftheOpenstatementis:

Open"FileName"For{Input|Output|Append|Random}As#FileNumber[Len=RecLength]

whereFileNamestandsfortheactualfilenameofthefile.AnabsoluteDOSdirectorypathshouldbeincludedasastringliteralorastring
expressionamountingtothesame.Examples:
Open"C:\HighScores.txt"ForInputAs#1opensafilenamed"HighScores.txt"thatislocatedintherootCdirectory.Itisbeing
openedforinputwhichmeansthatthedatathatisalreadyinthefilecanbereadandusedbytheVBprogram.The#1isthefilenumber
thattheprogrammerdecidedtouseintheVBprogramtorefertoHighScores.txt.Usuallythefirstdatafilethatisopenedislabelled#1
forconvenience.IfmorethanonefileisopenedbyaVBprogramatonce,filenumbersmustbeunique.Ifafilenamed"HighScores.txt"
cannotactuallybefoundinthecurrentdirectory,anerrormessagewilloccur.Thefilenumbersimplymarksthechannelthroughwhich
VBwillcommunicatewiththeparticularfile.
Open"A:\Names.dat"ForOutputAs#2opensafilenamed"Names.dat"thatislocatedonafloppydisksinceitiscommonfor
theA:drivetobethedrivelabelforafloppydriveonPC's.InthiscasethefileisbeingopenedforoutputwhichmeansthattheVB
programcanwritedatatothatfile.AnytimethatafileisbeingusedbyaVBprogram,afilepointermarksthecurrentactivelocationin
thatfile.Inthecaseofasequentialfilebeingopenedforoutput,thefilepointerpointstothebeginningofthefilesothefirstpieceof
datathatiswrittentothefilewillbeoverwritten.Ifasequentialfileisopenedforoutput,youcannotreadfromthefileatthesametime
withoutclosingitfirstandreopeningitforinput.
Open"C:\Temp\Data.txt"ForAppendAs#3opensafilenamed"Data.txt"thatislocatedintheTempdirectoryonthecomputer's
harddrive(sinceC:commonlyreferstoaPC'sprimaryharddrive).ItistypicalforPCprogrammerstostorefilesinacomputers
C:\Tempfolder.ThisfileisbeingopenedinAppendmodewhichmeansthatthefilepointerinitiallypointstotheendofthefileandwill
allowtheVBprogramtowritenewdatatothefilewithoutoverwritingpreviouslyexistingdata.Youcannotreaddatafromasequential
filethathasbeenopenedinAppendmode.
Open"StudentData.dat"ForRandomAs#4Len=50opensafilenamed"StudentData.dat"asarandomaccessfile.The
previousexampleswereallsequentialfiles.Randomaccessfilescanbereadfromorwrittento(i.e.areopenforinputand/oroutput)by
theVBprogram.TheLen=50indicatesthattherecordsizeforeachrecordisfixedas50bytes.ThissizemustbespecifiedsothatVB

http://www.minich.com/education/racc/visualbasic/cis230ch10/ch10notes1.htm 1/4
1/29/2017 VisualBasicCh.10Notes,page1

knowswheretoreadorwritedatawhentheprogrammeraccessesrecordsatrandom.(EventhoughtheLenfunctionreturnsthenumber
ofcharactersinastring,itreturnsthenumberofbytesinauserdefinedtypevariable,wherecharactersinastringarecountedas1byte
each.)
YoucancreateadatafilefromwithinaVBapplication,aswell.UsingtheOpenstatementwillautomaticallycreateafilewiththegivenname
aslongasitisnotbeingopenedinInputmode.Makesurethatyouhavechosenauniquefilenameoranotherpreviouslycreatedfilecould
accidentallybeoverwritten.
EachfileusedinaVBprogrammustbegivenafilenumberasdescribedabove.Itisconvenienttousesmallcountingnumbers1,2,3,etc.as
filenumbers.Ifyouarenotsurewhatthenextavailableintegerisatapointinaprogram,youcanusetheFreeFilefunctiontoassignthenext
lowestnumbertoanewlyopenedfile.ThestatementOpen"C:\Temp\Next.dat"ForOutputAsFreeFilewouldassignthesmallest
availablefilenumbertothedatafileNext.dat.However,itwouldbewisetofirstassignthenumbergeneratedbytheFreeFilefunctiontoa
variablewhichcouldbeusedlaterintheprogramwiththegivenfileasin:

intFileNumber=FreeFile
Open"C:\Temp\Next.dat"ForOutputAs#intFileNumber

Objective#2:Readandwriterecordstoadisk.

Forsequentialfiles,youusetheInput#statementtoinputcommadelimiteddatafromanexternaldatafile.
Foreachopensequentialfile,VBassociatesafilepointerwiththefile.Thefilepointerbeginsbymarking(i.e.pointingto)thefirstcharacterin
thedatafile.ToreadthecontentsofthefirstlineandtostorethemintoastringvariablenamedstrWord,thisstatementcanbeused:Input#1,
strWordThefilenumber#1isnecessarytoindicatethefilethatistobereadsincemorethanonefilemaybeopenedforinputatagiven
time.ThefirstpieceofdatawillbestoredinthestringvariablestrWord.Commasareusedtodelimitrecordsinsequentialaccessfiles.Thefile
pointerwouldthenpointtothenextpieceofdataonthesamelineifacommawaspresent.Otherwisethefilepointerwouldpointtothefirst
byteorcharacteronthenextlineofthedatafile.
Forsequentialfiles,youshouldusetheWrite#statementtooutputdatatoafileintheformofrecordsofvaryinglengths.(ThePrint#
statementcanbeusedaswellbutismoresuitedforwritingdisplayformatteddata.)
Foreachopensequentialfile,VBassociatesafilepointerwiththefile.Ifthefilewasopenedforoutput,thefilepointerstartedbypointingto
thefirstbyteofthefile.Therefore,tooverwriteanythingthathappenedtobeonthefirstlineofafilewiththestring"Hello",youwouldusea
statementlike:Write#1,"Hello"ifthefilewasopenedasfilenumber1.ThestatementWrite#1,"Hello","world"would
causethefirstlineofthesequentialfiletobe"Hello","world"wherethecommaservesasadelimiterbetweenfields.Thecarriagereturn,
Chr(13),andnewline,Chr(10),charactersarereadbytheInput#statementbutarenotsavedintothereceivingvariable.Theyarediscarded.
Tofindtheendofasequentialdatafile,itisconvenienttousetheEOFfunction.Attheendofeveryfile,anEOFcharacter(ormark)isused
toindicatetheactualend.Thefollowingcodeexcerptcouldbeusedtoassigneachrecordofasequentialfiletoseparateitemsofacombobox:

DoUntilEOF(1)
Input#1,strNext
cboSample.AddItemstrNext
Loop

TheloopcontinuesuntilEOF(1)istrue.EOF(1)istrueassoonasfilenumber#1wouldreadtheEOFcharacterasthenextcharacter.

http://www.minich.com/education/racc/visualbasic/cis230ch10/ch10notes1.htm 2/4
1/29/2017 VisualBasicCh.10Notes,page1

Objective#3:Determinetheappropriatelocationsfordatafilerelatedcode.

SincewedidnotstudyCh.9,youwillnotberesponsibleforthisobjective.

Objective#4:UnderstandthesignificanceofaClosestatement.

ItisalwaysagoodideatocloseanydatafilesthatwereopenedbyaVBprogrambeforeitends.Tocloseaspecificfilepreviouslyopenedas
filenumber1,usethestatementClose#1.Toclosetwofilesopenedasfilenumbers1and2,thestatementClose#1,#2canbeused.
Tocloseallopenfilesatonce,simplyuseClose.
WhileaVBprogramcouldendwithoutspecificallyclosinganyexternaldatafilesthatitused,thisisconsideredbadpractice.Youcouldlose
certainchangestothosefilesoryoucouldevendamageafiletoapointwhereitcannolongerbeopened.

Objective#5:Differentiatebetweensequentialandrandomfiles.

Sequentialfilesstoretextdatathatisseparatedintorecords.Recordsonthesamelineareseparatedbycommashowevercarriagereturn&new
linecharactersseparaterecordsonconsecutivelines.
Randomaccessfilesstoretextdatathatisseparatedintorecordsaswellhowevereachrecordmustbethesamesize.Withinthestructureofthe
record,anynumberoffieldscanbeusedtoseparatedifferentdatatypes.
Asequentialfileisusedlikeanaudiocassettetape.Datamustbeaccessedinorderfromthefirstpiecethroughtothelast.
ArandomaccessfileisusedlikeanaudioCDROM.Anypieceofdatacanbeaccessedatanytimewithoutnecessarilyaccessingeverypiece
ofdatathathappenstobelocatedclosertothebeginningofthefile.
Randomaccessfilesusuallyrequirethatyoucreateanddeclareauserdefineddatatypeinthegeneraldeclarationssectionofaformmodule.
Theadvantagesofrandomaccessfilesarethatitisfasttolocatedata.Also,itmaybeeasiertoupdatecodewrittentoworkforrandomaccess
files.Theadvantagesofsequentailfilesarethattheyareonlyusethespacerequiredbytheactualnumberofbytespresentinthefile.

Objective#6:Trapusererrorsandhandleerrorstoavoidruntimeerrors.

Youwillnotberesponsibleforthisobjectivethissemester.

Objective#7:Incorporatefixedlengthstringsintouserdefineddatatypes.

Stringvariablescanbedeclaredtobedynamicorfixedlength.
Adynamicstringvariableissimplydeclaredwithastatementsuchas:DimstrNameAsStringwherestrNamecanholdasmany
charactersasdesired.Itcanalsochangeinsizethroughouttheprogram.
Itispossibletodeclareastringvariabletoholdamaximumnumberofcharacters.ThedeclarationstatementDimstrNameAsString*
20declaresafixedstringvariablestrNametoasizethatitcanonlyhold20characters.Ifanattemptismadetoassignastringthatis
longerthan20characterstostrName,theoriginalstringwillbetruncatedandonlyitsfirst20characterswill"fit"intostrName.Ontheother
handifastringwithlessthan20charactersisassignedtostrName,thenblankspaceswillbeusedtopadthestringatthetailend.

Objective#8:Readandwriteobjectsinarandomfile.

Toreadorwriteobjectsinarandomfile,thefilemustbeopenedinrandomaccessmode.
http://www.minich.com/education/racc/visualbasic/cis230ch10/ch10notes1.htm 3/4
1/29/2017 VisualBasicCh.10Notes,page1

Whenafileisopenedinrandomaccessmode,arecordsizeisrequested.ThisallowsVBtowriteorreadspecificrecordsofthefilewithout
necessarilyreadingorwritingallofthepreviousdata.
UsethePutcommandtowritedatatoarandomaccessfile.ThegeneralformforthePutstatementis:Put[#]FileNumber,
[RecordNumber],RecordName.Examples:
Put#1,3,mudtStudentRecordthisstatementwritesthewholecontentsofthevariablemudtStudentRecordtothethirdrecordof
therandomaccessfile#1.
Put#2,,mudtStudentRecordthisstatementwritethewholecontentsofthevariablemudtStudentRecordtothenextavailable
recordoftherandomaccessfile#2,sincethelastGetorPuthadmovedthefilepointer.Noticethetwoconsecutivecommasinthe
middleofthestatement.
UsetheGetcommandtoobtaindata(i.e.read)fromarandomaccessfile.Youmuststorethedatathatyoureadintoauserdefineddatatype.
Examples:
Get#1,intStudentRecord,mudtStudentsgetsthenextavailablerecordandstoresitintointStudentRecords.
Get#2,,mudtStudentsgetsthenextavailablerecordandstoresitintheuserfdefineddatatype.
Sometimesitisnecessarytodeterminethesizeoftheuserdefineddatatypethatisbeingusedwithasequentialaccessfile.TheLOFfunction
canbeusedtodeterminethelengthofarecordasin:

intNumberRecords=LOF(1)/mudtStudentRecords
Fori=1tointNumberRecords
etc.

Objective#9:Performadd,delete,andeditoperationsonrandomfiles.

Comingsoon.

Objective#10:AllowtheusertoinputdatausingtheInputBoxfunction.

TheInputBoxfunctioncanbemoreconvenienttousetorequestinputtedinformationfromauserthanatextbox.WhiletheMsgBoxfunction
isusedtosimplydisplayamessagetotheuser,theInputBoxfunctionprovidesapromptandrequirestheusertoinputavalue.
ThegeneralformoftheInputBoxfunctionis:

VariableName=InputBox("Prompt"[,"Title"][,Default][,XPos][,YPos])
ThePromptisrequiredandcanbeastringliteralorastringexpression.TheTitleisthestringthatappearsinthetitlebaroftheinputbox.The
Defaultisthedefaultvaluethattheprogrammerwishestoappearintheinputareaoftheinputbox.XPosandYPosmarktheleftandtopedges
oftheinputbox.Ifthepromptislong,youmayusetheVBconstantvbCrLftomakeitappearonmultiplelines.

CIS230HomePage|Mr.Minich'sEducationHomePage|Minich.comWebDesign

http://www.minich.com/education/racc/visualbasic/cis230ch10/ch10notes1.htm 4/4

You might also like