General C Programming Examples.docx
- 文档编号:12031406
- 上传时间:2023-04-16
- 格式:DOCX
- 页数:77
- 大小:78.74KB
General C Programming Examples.docx
《General C Programming Examples.docx》由会员分享,可在线阅读,更多相关《General C Programming Examples.docx(77页珍藏版)》请在冰豆网上搜索。
GeneralCProgrammingExamples
GeneralCProgrammingExamples
TableofContents
Introduction
1.ProgramFormat
CProgramFormat
User-DefinedFunctionsinC
LoadRunnerScriptsandC
2.DataTypes
IntegerType
FloatType
CharType
FormatControl
Exercise2.1
3.ControlFlow
BooleanOperators
IfStatements
SwitchStatement
Exercise3.1
ForLoops
While
DoWhile
breakandcontinue
Exercise3.2
The?
operator
4.ArraysandStrings
Arrays
Strings
Exercise4.1
StringManipulation
Multi-DimensionalArrays
5.FileProcessing
FileDeclaration
FileOpening
FileReading
Exercise5.1
FileWriting
Exercise5.2
6.Functions
User-definedFunctions
Exercise6.1
IncludeFiles
Exercise6.2
7.MiscellaneousFunctions
System
RandomNumbers
Solutions
Exercise2.1
Exercise3.1
Exercise3.2
Exercise4.1
Exercise5.1
Exercise5.2
Exercise6.1
Introduction
MyinitialplanwastocreateaCreferencemanualfortheMercuryTestTeam.ThisisbecauseLoadRunnerscriptsconsistofcallstoLoadRunnerfunctions,whichareessentiallyCfunctionlibraries.SinceCformsthebasisforLoadRunnerscripts,mostofthefunctionsinCaresupportedinLoadRunner.ExpertiseinCwillhelpyoucustomizeandimprovethescriptsgreatly.SowethoughtthataCreferencemanualwouldbeveryuseful.
ThoughLoadRunnerisbasedonC,thereareafewvariationsandexceptionstotheCfunctionsthataresupportedinLoadRunner.Moreover,IdidnotwanttoaddtheoverheadofowningaCcompilertogothroughtheexercisesinthismanual.SoIthoughtI’dcreateamanualthatwouldworkwithVirtualUserGenerator(Vugen).Iamhopingthatbythetimeyougettothismanual,youarealreadyfamiliarwiththecomponentsofLoadRunner.
AllexercisesinthismanualcanbecompiledandruninVugen.AsIdiscusseachtopicinC,I’llalsodiscusshowitdiffersinLoadRunnerandthecontextinwhichthisfunctionmightbeuseful.ThiswillbothfamiliarizeyouwithCfromaLoadRunnerperspective,andmakeyoucomfortablewithusingcustomcodinginLoadRunner.
IfyouarealreadycomfortablewithC,youmightbeabletoskimthroughthismanualinnotime.PleasenotethatthepurposeofthismanualisnottomakeaCexpertoutofyou;mostoftheconceptsandexercisesinhereareveryelementary.ThiswilljustbeaquickC/LoadRunnerreference.
Hopeyoufindthisworkuseful.
1.ProgramFormat
Inthissection,wewilldiscusstheCprogramformatandhowitrelatestoLoadRunner.
CProgramFormat
Everyprogramminglanguagehasasetofrules,calledsyntaxofthelanguage,thatgovernhowlegalprogramsareconstructed.AprograminCcanbemadeupofmanycomponents,sometimesspreadoverseveralfiles.
WewilltakealookataverysimplebutpopularCprogram:
#include
main()
{
/*Thisprogramprints
“HelloWorld!
”*/
printf(“HelloWorld!
”);
}
Thefirstline,#include,isasignalthatsomeinformationshouldbeaddedtotheprogramfromanexternalfile,eitherasystemfileasinthiscase(
Thebodyoftheprogramiscontainedinmain(),encapsulatedby{}.
CommentsinCaresurroundedby/*and*/.TheCcompilerignoresalltextwithinthecomments.
Theonlystatementintheprogram,printf(“HelloWorld!
”)instructstheprogramtoprintthe“HelloWorld!
”tothestandardoutput.Now,thefunctionprintfisdefinedinstdio.h,andthatisthereasonweincludedstdio.habovethemain.
User-DefinedFunctionsinC
WeareviolatingeveryruleintheartofC-instructionbyintroducinguser-definedfunctionssoearlyinthegame.Butitisveryimportanttounderstanduser-definedfunctionstointroducehowLoadRunnerscriptstieintoCprogramming.Atthispoint,wewillintroduceuser-definedfunctionsataconceptuallevel,andgetintothedetailsinalatersection.
IntheHelloWorldprogram,weusedthefunctionprintf,whichprintsthegivenmessagetothestandardoutput.Theprintffunctionisastandardbuilt-infunctioninC.Sothecompilerunderstandstheactionrequestedbytheuseofthatfunction.Butitisoftennecessaryinprogrammingtocreateyourownfunctionstoaccomplishcertaintasks.Thesefunctionsarecalleduser-definedfunctions.
Forexample,letssayyouhavetoprintthefollowingtextanumberoftimesinyourprogram:
$$$$$$$$$$$
HelloWorld!
$$$$$$$$$$$
Thiscanbeaccomplishedbycreatingafunctionthatwillprinttheabovetextandcallingthefunctionanumberoftimesasrequired.
Thisiswhatyourprogramwilllooklike:
#include
my_function()
{
/*Textgeneratingcode*/
printf(“$$$$$$$$$$$\n”);
printf(“HelloWorld!
\n”);
printf(“$$$$$$$$$$$\n\n”);
}
main()
{
my_function();/*call1*/
printf(“Thisprogramdemonstratesuser-definedfunctions.\n\n”);
my_function();/*call2*/
}
Intheaboveprogram,wedefinedafunctionnamedmy_function,whichwascalledtwiceinthemain(call1andcall2).Thefollowingwillbetheoutputoftheaboveprogram.Youcanseethateverytimethefunctionmy_functionwascalled,the3-linetextoutputwasgenerated.
$$$$$$$$$$$
HelloWorld!
$$$$$$$$$$$
Thisprogramdemonstratesuser-definedfunctions
$$$$$$$$$$$
HelloWorld!
$$$$$$$$$$$
Bycreatingafunctiontogeneratethetextoutput,weavoidedtheneedtowritethetext-generatingcodeoverandoverinthemainprogram.Wecansimplycallthefunctionasmanytimesasweneed.
Theaboveisatrivialexampleofauser-definedfunctionwithasinglepurpose.Multi-purposeandreusablefunctionscanbecreatedbyuseofparameters.Thiswillbediscussedinalatersection.
NowthatwehaveanideaofwhataCfunctionis,letuslookathowLoadRunnerscriptsrelatetoC.
LoadRunnerScriptsandC
InVugen,youmayhavenoticedthataLoadRunnerscriptconsistsofinit,actionsandendsections.InLoadRunner6.0andabove,youcanhavemultipleactionssectionsasshowninfigure1.1.
Figure1.1:
Vugen
LetslookattheabovescriptfromaCprogrammingpointofview.WhenyourecordascriptintodifferentsectionsofVugen,eachsectionwillberecordedlikearegularCfunction.Intheabovefigure,vuser_init,Action1,Action2andvuser_endwillbeour4functions.Iftheabovescriptissettorun3iterations,thisishowanequivalentCprogramwouldlooklike:
main()
{
/*callinginitsection*/
vuser_init();
/*callingactionssectioniteration1*/
Action1();
Action2();
/*callingactionssectioniteration2*/
Action1();
Action2();
/*callingactionssectioniteration3*/
Action1();
Action2();
vuser_end();
}
whereeachfunctionisdefinedintheVugenscript.ThereisnomaininLoadRunner.Itisautomaticallytakencareofbehindthescenes.Differentsectionsofthescriptsaretheonlyvisiblepartsoftheprogram.
Whatgoesonbehindthescenesisalotmoreugly,buttheaboveisasimplisticrepresentationoftheidea.Thevuserwillexecuteallactionscorrespondingtothatsectionwhenafunctioniscalled.Itisimportanttounderstandthateachsectioninthescriptistreatedlikeauser-definedfunction.
Example:
Intheabovescript,letssayeachsectionprintsamessageidentifyingitself.ThefollowingwillbetheoutputintheexecutionlogofVugen:
VirtualUserScriptstarted
vuser_init.c(3):
Youareinvuser_init
RunningVuser...
Startingiteration1.
Action1.c(3):
YouareinActions1
Action2.c(3):
YouareinActions2
Endingiteration1.
Startingiteration2.
Action1.c(3):
YouareinActions1
Action2.c(3):
YouareinActions2
Endingiteration2.
Startingiteration3.
Action1.c(3):
YouareinActions1
Action2.c(3):
YouareinActions2
Endingiteration3.
EndingVuser...
vuser_end.c(3):
Youareinvuser_end
VuserTerminated.
Inarealscript,eachofthesefunctionsmightbeexercisingtheapplicationundertest(AUT),ratherthanjustprintingprettylittlemessages.
TheideabehindthischapterwasjusttofamiliarizeyouwiththeLoadRunnerprogramstructureandcompareittoC.WewillfocusondifferentelementsofCintheupcomingsections.
2.DataTypes
Ithink“HelloWorld”istheonlyrespectedprogramintheworldthatdoesnotcontainvariables.Ifyouwantyourprogramtodoanythingremotelyinteresting,youwillhavetousevariables.Inthischapter,wewillseethedifferentdatatypesinwhichavariablecanbedeclared.
Forexample,avariablecalledcountcanbedeclaredasanintegertype.
intcount=0;
Nowthevariablecountcanassumeanyintegervalueduringtheprogramexecution.Therearelimitationsonthesizeandprecisionofeachdatatype,whichwewilldiscussshortly.AllvariablesinCmustbedeclaredbeforetheycanbeused.
IntegerType
Asthenamesuggests,thistypeisusedtodeclarevariablestocontainintegervalues.Typically,shortintegersrangeinvaluesbetween–32,768to32767(Theprecisiondependsonthenumberofbitsused).Longinteger,orjustdeclaredasintinLoadRunner,rangesinvaluesfrom–2147483648to2147483648(Noshortageofvaluesthere!
).Unlessyouareusingawholelotofvariables,whichisnotthecasetypicallyinLoadRunner,youdon’thavetoworryaboutmemoryconsiderations.Butnotethatashortinttakeslesserspaceinmemorycomparedtoaregularinteger.
FloatType
Floattypeisusedfornon-integralvaluesliketheonebelow:
floatx=2.564;
Floatrangesinvaluesfrom10-38to1038.Forgreaterrange,youcanusedouble,whichrangesinvaluesfrom10-308to10308.Wewillrarelyneedthisdatat
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- General Programming Examples
![提示](https://static.bdocx.com/images/bang_tan.gif)