You are on page 1of 10

CTutorial

Thisguideattemptstooutlineafewthingsthatmayhelpyouget startedwiththeCprogramminglanguage,Itisnotmeanttoactasa completetutorial,insteaditisaguideforthosewhoalreadyknowC++. IfyouhaveneverprogrammedinCbeforeandthisguideisnot enoughtohelpyou,IstronglysuggestthatyoubuyacopyofTheC ProgrammingLanguagesecondedition,byKernighanandRitchie.A cheapcopycanusuallybefoundatwww.barnesandnoble.comor www.half.com.

CHelloWorld
Thefirstprogramthatyoualwaysstartwithwhenlearninganew languageishelloworld.

#include<stdio.h> int main() { printf("Hello World!\n"); return 0; }

You'llnoticethatCisverysimilartoC++.Oneofthemostnotable differencesistheuseoftheprintffunctionwhichisusedtoprint informationtothescreen.Cdoesnothavetheconceptofastream whichmeansthatcinandcoutcannotbeused. Theprintffunctioncanalsobeusedtoprintvariablesaswell. hereisanexample.


#include<stdio.h> int main() { int x = 5; printf("Hello World! x=%d\n", x); return 0; }

The'%d'insidethestringpassedtoprintfgetsreplacedwiththe

valueofthevariablepassedasthesecondargument(inthisexample,x). Ifyouneedtoprintacharacteryouplacea'%c'whereyouwantthat charactertoappear.Ifyouneedtoprintastringyouplacea'%s'where youwantthatcharactertoappear. Ifyouneedtoprintmorethanonevariableinasingleprintfcall yousimplyincludemultiple'%'statementsinyourstringandthengive alloftheneededargumentstoprintf,Hereisanexample.


#include<stdio.h> int main() { char* name = "Bob"; int age = 25; char mi = 'c'; printf("My name is %s, my age is %d and my middle initial is %c.\n", name, age, mi); return 0; }

Theprintffunctioncantakeasmanyargumentsasneededtoprint asmanyvariablesasyouwantbutkeepinmindthattheorderofthose variablesisveryimportant.Ourstringcontainsa%s,%d,and%cin thatparticularorder.Soprintfisexpectingtofindastring,aninteger, andacharacterasitssecond,thirdandfourtharguments.

Cstrings
Cdoesnothaveanofficial'string'datatype.Insteadstringsare implementedusinganarrayofcharacters.Hereisatypicalstring declarationandinitialization.
char* name = bob;

ComparingCstrings Sowhatifyouwanttocheckthevalueofastringtoseeifitis equaltofoo?Canyouusethefollowingcode?


char* x = bar; if(x == foo)

Absolutelynot!Remember,xisreallyapointertoacharacter.If youwishtocomparextofooyouwillhavetocompareeachandevery

characterofxtofoo.Youcaneasilywriteaforlooptodothis,oryou canusethestrcmpfunction.
#include<stdio.h> #include<string.h> /* printf */ /* strcmp */

int main() { char* x = "bar"; int retval = strcmp(x, "foo"); if (retval == 0) printf("The two strings are equal.\n"); else printf("The strings are NOT equal.\n"); return 0; }

Ifthestrcmpfunctionreturns0,thenthetwostringsareequal.If itreturnsanynumberotherthan0,thestringsarenotequal.Formore informationseethemanpageforstrcmp. Copying Sincestringsarejustarrayswhichareimplementedusing pointers,youcannotcreateacopyofastringwiththe=operator.This willjustcausethepointerpointingtothestringtobecopied.Ifyouwish todeepcopyastring,youwillneedtoeithercopyeachindividual character,orusethestrcpyfunction.


#include<stdio.h> #include<string.h> int main() { char* x = "hello"; char* y = (char*)malloc( sizeof(char) * 10 ); strcpy(y, x); int retval = strcmp(x, y); if (retval == 0) printf("The copy worked.\n"); else printf("The copy did NOT worked.\n"); free(y); return 0; }

Ignorethemalloc()linefornow.itjustcreatesastringofsize10.

Noticetheunusualorderofargumentsforstrcpy.Ittakesthe destinationstringasthefirstargumentandthesourcestringasthe secondargument. Stringlength Gettingthelengthofastringasaseasyasacalltostrlen.


#include<stdio.h> #include<string.h> int main() { char* x = "hello"; int length = strlen(x); printf("The string is of length %d\n", length); return 0; }

Stringconcatenation Concatenatingtwostringstogetherrequiresacalltostrcat.
#include<stdio.h> #include<string.h> int main() { char* x = (char*)malloc( sizeof(char) * 10 ); char* y = (char*)malloc( sizeof(char) * 10 ); strcpy(x,"he"); strcat(x,"llo"); printf("%s\n",x); free(x); free(y); return 0; }

Otherstringfunctions indexLocateacharacterinastring. Use'manstring'togetmoreinformation.

CommandLineArguments
ProcessingargumentsinCisverysimilartoprocessingarguments inC++.Hereisanexampleprogramthatwillprintoutallofit's argumentsonseparatelinesandthenterminate.
#include<stdio.h> #include<string.h> int main(int argc, char* argv[]) { printf("argv[0] (program name) = %s\n", argv[0]); int i; for(i=1; i < argc; i++) { printf("argv[%d] (argument %d) = %s\n", i ,i, argv[i]); } return 0; }

Theveryfirstargument(argv[0])willalwaysbethenameofthe program(executablefile)thatisbeingexecuted.Alloftheother argumentswillbeputinargv[1],argv[2],argv[3],etc.Theargcinteger tellsyouhowmanyargumentstoexpect.

Files
Inc++,youusedifstreamandofstreamtoaccessfiles.InC,we willuseothermethods.Youshouldinclude'stdio.h'toworkwiththe methodsdescribedbelow. Openingfiles Thefirstthingyouneedtodotoworkwithafileistoopenit.If youwanttoopenafileforreading,youwillneedalineofcodesimilarto this.
FILE* in = fopen("myfile.txt","r");

Thislineofcodecreatesafilepointerandthenusesthefopen functiontoobtainafilepointertomyfile.txtforreading.Ther representsthemodethatwewishtouseforopeningthefile.Moder allowsyoutoreadthefileandmodewallowsyoutowritethefile. Consultthe'fopen'manpageformoreinformationonfilemodes.

Readingfiles Nowthatyou'veopenedthefileforreading,youcanreadfromthe filewithavarietyofdifferentmethods.Tofindoutmoreaboutthese methodscheckthe'gets'manpage.Wewillbeusingthefgetcmethod whichallowsyoutoreadthroughafileonecharacteratatime.


#include<stdio.h> int main() { FILE * in = fopen("myfile.txt","r"); char currentCharacter; while(!feof(in)) { currentCharacter = fgetc(in); printf("%c", currentCharacter); } return 0; }

Writingfiles writingfilesissimilartoreadingthem.Insteadofgivingther modetofopen,yougiveitthewmode.Itisimportanttonotethatthe wmodewillcausethecontentsofthespecifiedfiletobedestroyed.If youwishtoappenddatayoushouldusetheamode. Justlikethereisacollectionofgetfunctionsforreadingdatafrom afile,thereisalsoacollectionofputfunctionsforwritingdatatoafile. Readthe'puts'manpageformoreinformation.Herewewillusethe fprintffunctionwhichallowsyoutowriteanentirestringtoafile.


#include<stdio.h> int main(int argc, char* argv[]) { if (argc < 2) { printf("This program writes its arguments to args.txt\n"); printf("You must specify at least one argument.\n"); } FILE * out = fopen("args.txt","w");

int i; for(i=1; i < argc; i++) { fprintf(out,"%s\n",argv[i]); } return 0; }

FilePositionIndicator Whenyouopenafilethefilepositionindicatorissettopointtothe firstcharacter/byteinthefile.Asyoureadthroughafile,thefile positionindicationisupdatedtopointtothenextcharacter.Ifyouread thefirst100bytes,thepositionindicatorwillpointtothe101st byte/characterofthefile. Therearemethodsavailableformanipulatingtheposition indicator.themostimportantoneisfseekwhichallowsyoutoskipover aspecifiednumberofbytesinafile.Formoreinformationonfseekand otherpositionindicatormanipulationfunctionsreadthemanpageon fseek. Note:Thesectiontitled'MemoryManagement'wastakenfromthe followinglocation:http://www2.sis.pitt.edu/~ir/KS/Data/RMiles/c13.html Thetexthasbeenslightlymodifiedinsomeplacesputthemateriallargely remainsthesame.

MemoryManagement
Sometimesyouwillcomeacrosssituationswhereyoudonotknow whentheprogramrunsexactlyhowmuchmemoryyourprogramwill need,forexampleyoumaywanttheusertotellyouhowmanyitemshe orshewantstostore,andthengetachunkofmemoryjusttheright size.Thisisthemostefficientwayofwritingyourprograms,itmeans thatyoudonotusemoreresourcesthanrequired.WhenaCprogram runs,anumberofservicesaremadeavailabletoitbythesystemitis runningon.Oneoftheseisamemorymanager.Thememorymanager looksafterwhatmemoryisusedbywho.Onasingleusersystem,like theIBMPC,thisisaverysimpleaffair,eitheryouhavethememoryor thesystemdoes.Onamultiusersystem,likeUNIX,thingsarealot morecomplicated.Youhoweverdonotneedtoworryaboutthis,you simplyaskthememorymanagerforachunkofmemoryanditwillgive ittoyouifthereisenoughleft.Whenyouhavefinishedwiththe

memory,itisniceifyougiveitbacksothatotherprogramscanuseit. Theincludefile'alloc.h'containsallthememoryallocation routines.Youcanfindouthowmuchmemoryisleft,thesizeofthe biggestblockavailableandthingslikethat.Weareonlygoingtousetwo, mallocandfree. malloc Thisfunctionwilltrytogetachunkofmemoryforyou.Itreturnsa pointertothememoryitfound,ifitcouldgetsome.Ifnotitreturnsa NULLpointer.Youmustalwayschecktomakesurethatmallocworked beforeyouusethememoryyouthinkyougot!mallochasoneparameter, thesizeoftheblockofmemoryyouwant.Youcanusesizeoftofindout howmuchmemoryyouneed,forexample:
sizeof( int)*99

Thiswouldbeenoughspacefor99integers.Becausemalloc returnsapointertoanitemoftypevoidyoumustusethecastfacilityto makethiscompatiblewiththetypeyoureallywant;i.e.ifyouwantto store99integersyouwillhaveapointertointegerswhichyouwantto makepointattheblockofmemorywhichmallocisgoingtogetforyou. Thecastwillmakesurethatthecompilerdoesnotproduceanerror whenitseestheassignment,forexample:


int* buffer; buffer = (int*)malloc(sizeof(int) * 99); if ( buffer == NULL ) { printf("No memory!\n") ; } else { /****** do something with the memory... *******/ }

IwouldaccessaniteminbufferinexactlythesamewayasIwould accesselementsinanyblockofmemoryorarray,forexamplebuffer[20]. Notethattheeffectsofgoingovertheendofablockofmemorywhich hasbeenfetchedinthiswayasjustthesameasanyotheryour programwilldostupidthingsandthenfallover!Notealsothatyouhave noideawhatisinthememorywhenyougetit!Donotassumethatit hasbeenemptiedofsillyvalues.Thereisafunction,calloc,whichyou canuseifyouwantallyourmemorytobeclearedbeforeyougetit.This functionisuseddifferentlyfrommalloc,soyouwillhavetolookitup.

free Whenyouhavefinishedwithsomememoryyoucangiveitbackto thememorymanagerbytheuseofthefreefunction,forexample:


free(buffer);

Thiswouldgivebackthememorywerequestedabove.Notethatif wetrytousethismemoryagain,itmayhavebeenusedforsomething elseandsothiswouldcausebigproblems.Itisgoodhousekeepingto alwaysgivebackmemorywhichyouhaveallocated.Ifyoudonotyou mightfindthatthetotalamountofmemoryavailablewilldroptoapoint whereyourprogramwillnotrunanymore.

OtherResources
Ifyouneedmoreinformationyoushouldcheckthefollowing resources. manpages Youcanusethe'man'commandunderLinux/Unixtoobtain usefulinformationaboutmanyCfunctionsandlibraries.Someofthe followingmaybeofinteresttoyou. strings strstr strlen strcpy strchr strcmp fopen fclose fread fwrite fprintf puts gets getcwd fork execvp wait waitpid kill(usethiscommand'man2kill') dup2 waitpid

Usefulwebsites Strings http://cermics.enpc.fr/~ts/C/FUNCTIONS/function.ref.html (lookatstring.hsection) Memorymanagement http://www2.sis.pitt.edu/~ir/KS/Data/RMiles/c13.html files http://www.cprogramming.com/tutorial/cfileio.html vergil.chemistry.gatech.edu/resources/programming/ctutorial/io.html CommandLineArguments http://www.eskimo.com/~scs/cclass/notes/sx13.html http://juicystudio.com/tutorial/c/command.asp ProcessControl http://jan.netcomp.monash.edu.au/ssw/processes/unix.html http://www.cs.uleth.ca/~holzmann/C/system/pipeforkexec.html http://www.dgp.toronto.edu/~ajr/209/notes/proc.html General http://www2.sis.pitt.edu/~ir/KS/Data/RMiles/contents.html http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/ http://www.its.strath.ac.uk/courses/c/ Books TheCProgrammingLanguagesecondedition BrianWKernighan&DennisM.Ritchie PrenticeHall
http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?isbn=0131103628

You might also like