You are on page 1of 151

BASH Programming - Introduction HOW-

TO
by Mike G mikkey at dynamo.com.ar
Thu Jul 27 09:36:18 ART 2000

This article intends to help you to start programming basic-intermediate shell scripts.
It does not intend to be an advanced document (see the title). I am NOT an expert nor
guru shell programmer. I decided to write this because Ill learn a lot and it might be
useful to other people. Any feedback will be apreciated, specially in the patch form .)

Introduction
O 1.1 Getting the latest version
O 1.2 Requisites
O 1.3 Uses oI this document
2 Very simple Scripts
O 2.1 Traditional hello world script
O 2.2 A very simple backup script
3 All about redirection
O 3.1 Theory and quick reIerence
O 3.2 Sample: stdout 2 Iile
O 3.3 Sample: stderr 2 Iile
O 3.4 Sample: stdout 2 stderr
O 3.5 Sample: stderr 2 stdout
O 3.6 Sample: stderr and stdout 2 Iile
4 Pipes
O 4.1 What they are and why you'll want to use them
O 4.2 Sample: simple pipe with sed
O 4.3 Sample: an alternative to ls -l *.txt
5 Variables
O 5.1 Sample: Hello World! using variables
O 5.2 Sample: A very simple backup script (little bit better)
O 5.3 Local variables
6 Conditionals
O 6.1 Dry Theory
O 6.2 Sample: Basic conditional example iI .. then
O 6.3 Sample: Basic conditional example iI .. then ... else
O 6.4 Sample: Conditionals with variables
7 Loops for, while and until
O 7.1 For sample
O 7.2 C-like Ior
O 7.3 While sample
O 7.4 Until sample
8 Functions
O 8.1 Functions sample
O 8.2 Functions with parameters sample
9 User interfaces
O 9.1 Using select to make simple menus
O 9.2 Using the command line
Misc
O 10.1 Reading user input with read
O 10.2 Arithmetic evaluation
O 10.3 Finding bash
O 10.4 Getting the return value oI a program
O 10.5 Capturing a commands output
O 10.6 Multiple source Iiles
Tables
O 11.1 String comparison operators
O 11.2 String comparison examples
O 11.3 Arithmetic operators
O 11.4 Arithmetic relational operators
O 11.5 UseIul commands
2 More Scripts
O 12.1 Applying a command to all Iiles in a directory.
O 12.2 Sample: A very simple backup script (little bit better)
O 12.3 File re-namer
O 12.4 File renamer (simple)
3 When something goes wrong (debugging)
O 13.1 Ways Calling BASH
4 About the document
O 14.1 (no) warranty
O 14.2 Translations
O 14.3 Thanks to
O 14.4 History
O 14.5 More resources
Introduction
Getting the latest version
http://www.linuxdoc.org/HOWTO/Bash-Prog-Intro-HOWTO.html
2 Requisites
Familiarity with GNU/Linux command lines, and Iamiliarity with basic programming
concepts is helpIul. While this is not a programming introduction, it explains (or at
least tries) many basic concepts.
3 Uses of this document
This document tries to be useIul in the Iollowing situations
O ou have an idea about programming and you want to start coding some shell
scripts.
O ou have a vague idea about shell programming and want some sort oI
reIerence.
O ou want to see some shell scripts and some comments to start writing your
own
O ou are migrating Irom DOS/Windows (or already did) and want to make
"batch" processes.
O ou are a complete nerd and read every how-to available
O 2 Very simple Scripts
O This HOW-TO will try to give you some hints about shell script programming
strongly based on examples.
O In this section you'll Iind some little scripts which will hopeIully help you to
understand some techniques.
O 2 Traditional hello world script
O #!/bin/bash
O echo Hello World
O
O This script has only two lines. The Iirst indicates the system which program to
use to run the Iile.
O The second line is the only action perIormed by this script, which prints 'Hello
World' on the terminal.
O II you get something like ./hello.sh. Command not found. Probably the Iirst line
'#!/bin/bash' is wrong, issue whereis bash or see 'Iinding bash' to see how sould
you write this line.
O 22 A very simple backup script
O #!/bin/bash
O tar -cZf /var/my-backup.tgz /home/me/
O
O In this script, instead oI printing a message on the terminal, we create a tar-ball
oI a user's home directory. This is NOT intended to be used, a more useIul
backup script is presented later in this document.
3 All about redirection
3 Theory and quick reference
There are 3 Iile descriptors, stdin, stdout and stderr (stdstandard).
Basically you can:
1. redirect stdout to a Iile
2. redirect stderr to a Iile
3. redirect stdout to a stderr
4. redirect stderr to a stdout
5. redirect stderr and stdout to a Iile
6. redirect stderr and stdout to stdout
7. redirect stderr and stdout to stderr
1 'represents' stdout and 2 stderr.
A little note Ior seeing this things: with the less command you can view both stdout
(which will remain on the buIIer) and the stderr that will be printed on the screen, but
erased as you try to 'browse' the buIIer.
32 Sample: stdout 2 file
This will cause the ouput oI a program to be written to a Iile.
ls -l ls-l.txt

Here, a Iile called 'ls-l.txt' will be created and it will contain what you would see on
the screen iI you type the command 'ls -l' and execute it.
33 Sample: stderr 2 file
This will cause the stderr ouput oI a program to be written to a Iile.
grep da 2 grep-errors.txt

Here, a Iile called 'grep-errors.txt' will be created and it will contain what you would
see the stderr portion oI the output oI the 'grep da *' command.
34 Sample: stdout 2 stderr
This will cause the stderr ouput oI a program to be written to the same Iiledescriptor
than stdout.
grep da 1&2

Here, the stdout portion oI the command is sent to stderr, you may notice that in
diIIeren ways.
35 Sample: stderr 2 stdout
This will cause the stderr ouput oI a program to be written to the same Iiledescriptor
than stdout.
grep 2&1

Here, the stderr portion oI the command is sent to stdout, iI you pipe to less, you'll see
that lines that normally 'dissapear' (as they are written to stderr) are being kept now
(because they're on stdout).
36 Sample: stderr and stdout 2 file
This will place every output oI a program to a Iile. This is suitable sometimes Ior cron
entries, iI you want a command to pass in absolute silence.
rm -f $(find / -name core) & /dev/null

This (thinking on the cron entry) will delete every Iile called 'core' in any directory.
Notice that you should be pretty sure oI what a command is doing iI you are going to
wipe it's output.
4 Pipes
This section explains in a very simple and practical way how to use pipes, nd why you
may want it.
4 What they are and why you'll want to use them
Pipes let you use (very simple, I insist) the output oI a program as the input oI another
one
42 Sample: simple pipe with sed
This is very simple way to use pipes.
ls -l | sed -e "s/aeio,/u/g"

Here, the Iollowing happens: Iirst the command ls -l is executed, and it's output,
instead oI being printed, is sent (piped) to the sed program, which in turn, prints what
it has to.
43 Sample: an alternative to ls -l `txt
Probably, this is a more diIIicult way to do ls -l *.txt, but it is here Ior illustrating
pipes, not Ior solving such listing dilema.
ls -l | grep "\.txt$"

Here, the output oI the program ls -l is sent to the grep program, which, in turn, will
print lines which match the regex "\.txt$".
5 Variables
ou can use variables as in any programming languages. There are no data types. A
variable in bash can contain a number, a character, a string oI characters.
ou have no need to declare a variable, just assigning a value to its reIerence will
create it.
5 Sample: Hello World! using variables
#!/bin/bash
STR="Hello World!"
echo $STR

Line 2 creates a variable called STR and assigns the string "Hello World!" to it. Then
the VALUE oI this variable is retrieved by putting the '$' in at the beginning. Please
notice (try it!) that iI you don't use the '$' sign, the output oI the program will be
diIIerent, and probably not what you want it to be.
52 Sample: A very simple backup script (little bit better)
#!/bin/bash
JF=/var/my-backup-$(date +%Y%m%d).tgz
tar -cZf $JF /home/me/

This script introduces another thing. First oI all, you should be Iamiliarized with the
variable creation and assignation on line 2. Notice the expression '$(date
md)'. II you run the script you'll notice that it runs the command inside the
parenthesis, capturing its output.
Notice that in this script, the output Iilename will be diIIerent every day, due to the
Iormat switch to the date command(md). ou can change this by speciIying
a diIIerent Iormat.
Some more examples:
echo ls
echo $(ls)
53 Local variables
Local variables can be created by using the keyword local.
#!/bin/bash
HELLJ=Hello
function hello ,
local HELLJ=World
echo $HELLJ
,
echo $HELLJ
hello
echo $HELLJ

This example should be enought to show how to use a local variable.
6 Conditionals
Conditionals let you decide whether to perIorm an action or not, this decision is taken
by evaluating an expression.
6 Dry Theory
Conditionals have many Iorms. The most basic Iorm
is: if expression then statement where 'statement' is only executed iI 'expression'
evaluates to true. '21' is an expresion that evaluates to Ialse, while '2~1' evaluates to
true.xs
Conditionals have other Iorms such as: if expression then statement1 else statement2.
Here 'statement1' is executed iI 'expression' is true,otherwise 'statement2' is executed.
et another Iorm oI conditionals is: if expression1 then statement1 else
if expression2 then statement2 else statement3. In this Iorm there's added only the
"ELSE IF 'expression2' THEN 'statement2'" which makes statement2 being executed
iI expression2 evaluates to true. The rest is as you may imagine (see previous Iorms).
A word about syntax:
The base Ior the 'iI' constructions in bash is this:
iI |expression|;
then
code iI 'expression' is true.
Ii
62 Sample: Basic conditional example if then
#!/bin/bash
if "foo" = "foo" ,; then
echo expression evaluated as true
fi

The code to be executed iI the expression within braces is true can be Iound aIter the
'then' word and beIore 'Ii' which indicates the end oI the conditionally executed code.
63 Sample: Basic conditional example if then else
#!/bin/bash
if "foo" = "foo" ,; then
echo expression evaluated as true
else
echo expression evaluated as false
fi

64 Sample: Conditionals with variables
#!/bin/bash
T1="foo"
T2="bar"
if "$T1" = "$T2" ,; then
echo expression evaluated as true
else
echo expression evaluated as false
fi

7 Loops for, while and until
In this section you'll Iind Ior, while and until loops.
The for loop is a little bit diIIerent Irom other programming languages. Basically, it
let's you iterate over a series oI 'words' within a string.
The while executes a piece oI code iI the control expression is true, and only stops
when it is Ialse (or a explicit break is Iound within the executed code.
The until loop is almost equal to the while loop, except that the code is executed
while the control expression evaluates to Ialse.
II you suspect that while and until are very similar you are right.
7 For sample
#!/bin/bash
for i in $( ls ); do
echo item: $i
done

On the second line, we declare i to be the variable that will take the diIIerent values
contained in $( ls ).
The third line could be longer iI needed, or there could be more lines beIore the done
(4).
'done' (4) indicates that the code that used the value oI $i has Iinished and $i can take
a new value.
This script has very little sense, but a more useIul way to use the Ior loop would be to
use it to match only certain Iiles on the previous example
72 C-like for
Iiesh suggested adding this Iorm oI looping. It's a Ior loop more similar to C/perl...
Ior.
#!/bin/bash
for i in `seq 1 10`;
do
echo $i
done

73 While sample
#!/bin/bash
CJUNTER=0
while $CJUNTER -lt 10 ,; do
echo The counter is $CJUNTER
let CJUNTER=CJUNTER+1
done

This script 'emulates' the well known (C, Pascal, perl, etc) 'Ior' structure
74 Until sample
#!/bin/bash
CJUNTER=20
until $CJUNTER -lt 10 ,; do
echo CJUNTER $CJUNTER
let CJUNTER-=1
done

8 Functions
As in almost any programming language, you can use Iunctions to group pieces oI
code in a more logical way or practice the divine art oI recursion.
Declaring a Iunction is just a matter oI writing Iunction myIunc mycode }.
Calling a Iunction is just like calling another program, you just write its name.
8 Functions sample
#!/bin/bash
function quit ,
exit
,
function hello ,
echo Hello!
,
hello
quit
echo foo

Lines 2-4 contain the 'quit' Iunction. Lines 5-7 contain the 'hello' Iunction II you are
not absolutely sure about what this script does, please try it!.
Notice that a Iunctions don't need to be declared in any speciIic order.
When running the script you'll notice that Iirst: the Iunction 'hello' is called, second
the 'quit' Iunction, and the program never reaches line 10.
82 Functions with parameters sample
#!/bin/bash
function quit ,
exit
,
function e ,
echo $1
,
e Hello
e World
quit
echo foo


This script is almost identically to the previous one. The main diIIerence is the
Iuncion 'e'. This Iunction, prints the Iirst argument it receives. Arguments, within
Iuntions, are treated in the same manner as arguments given to the script.
9 User interfaces
9 Using select to make simple menus
#!/bin/bash
JPTIJNS="Hello Quit"
select opt in $JPTIJNS; do
if "$opt" = "Quit" ,; then
echo done
exit
elif "$opt" = "Hello" ,; then
echo Hello World
else
clear
echo bad option
fi
done

II you run this script you'll see that it is a programmer's dream Ior text based menus.
ou'll probably notice that it's very similar to the 'Ior' construction, only rather than
looping Ior each 'word' in $OPTIONS, it prompts the user.
92 Using the command line
#!/bin/bash
if -z "$1" ,; then
echo usage: $0 directory
exit
fi
SRCD=$1
TGTD="/var/backups/"
JF=home-$(date +%Y%m%d).tgz
tar -cZf $TGTD$JF $SRCD

What this script does should be clear to you. The expression in the Iirst conditional
tests iI the program has received an argument ($1) and quits iI it didn't, showing the
user a little usage message. The rest oI the script should be clear at this point.
Misc
Reading user input with read
In many ocations you may want to prompt the user Ior some input, and there are
several ways to achive this. This is one oI those ways:
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"

As a variant, you can get multiple values with read, this example may clariIy this.
#!/bin/bash
echo Please, enter your firstname and lastname
read FN LN
echo "Hi! $LN, $FN !"

2 Arithmetic evaluation
On the command line (or a shell) try this:
echo 1 1
II you expected to see '2' you'll be disappointed. What iI you want BASH to evaluate
some numbers you have? The solution is this:
echo $((11))
This will produce a more 'logical' output. This is to evaluate an arithmetic expression.
ou can achieve this also like this:
echo $|11|
II you need to use Iractions, or more math or you just want it, you can use bc to
evaluate arithmetic expressions.
iI i ran "echo $|3/4|" at the command prompt, it would return 0 because bash only
uses integers when answering. II you ran "echo 3/4,bc -l", it would properly return
0.75.
3 Finding bash
From a message Irom mike (see Thanks to)
you always use #!/bin/bash .. you might was to give an example oI
how to Iind where bash is located.
'locate bash' is preIerred, but not all machines have locate.
'Iind ./ -name bash' Irom the root dir will work, usually.
Suggested locations to check:
ls -l /bin/bash
ls -l /sbin/bash
ls -l /usr/local/bin/bash
ls -l /usr/bin/bash
ls -l /usr/sbin/bash
ls -l /usr/local/sbin/bash
(can't think oI any other dirs oIIhand... i've Iound it in
most oI these places beIore on diIIerent system).
ou may try also 'which bash'.
4 Getting the return value of a program
In bash, the return value oI a program is stored in a special variable called $?.
This illustrates how to capture the return value oI a program, I assume that the
directory dada does not exist. (This was also suggested by mike)
#!/bin/bash
cd /dada & /dev/null
echo rv: $.
cd $(pwd) & /dev/null
echo rv: $.

5 Capturing a commands output
This little scripts show all tables Irom all databases (assuming you got MySQL
installed). Also, consider changing the 'mysql' command to use a valid username and
password.
#!/bin/bash
DBS=`mysql -uroot -e"show databases"`
for b in $DBS ;
do
mysql -uroot -e"show tables from $b"
done

6 Multiple source files
ou can use multiple Iiles with the command source.
TO-DO
Tables
String comparison operators
(1) s1 s2
(2) s1 ! s2
(3) s1 s2
(4) s1 ~ s2
(5) -n s1
(6) -z s1
(1) s1 matches s2
(2) s1 does not match s2
(3) TO-DO
(4) TO-DO
(5) s1 is not null (contains one or more characters)
(6) s1 is null
2 String comparison examples
Comparing two strings.
#!/bin/bash
S1='string'
S2='String'
if $S1=$S2 ,;
then
echo "S1('$S1') is not equal to S2('$S2')"
fi
if $S1=$S1 ,;
then
echo "S1('$S1') is equal to S1('$S1')"
fi

I quote here a note Irom a mail, sent buy Andreas Beck, reIering to use if [ $1 $2 ].
This is not quite a good idea, as iI either $S1 or $S2 is empty, you will get a parse
error. x$1x$2 or "$1""$2" is better.
3 Arithmetic operators

-
*
/
(remainder)
4 Arithmetic relational operators
-lt ()
-gt (~)
-le ()
-ge (~)
-eq ()
-ne (!)
C programmer's should simple map the operator to its corresponding parenthesis.
5 Useful commands
This section was re-written by Kees (see thank to...)
Some oI these command's almost contain complete programming languages. From
those commands only the basics will be explained. For a more detailed description,
have a closer look at the man pages oI each command.
sed (stream editor)
Sed is a non-interactive editor. Instead oI altering a Iile by moving the cursor on the
screen, you use a script oI editing instructions to sed, plus the name oI the Iile to edit.
ou can also describe sed as a Iilter. Let's have a look at some examples:
$sed 's/to_be_replaced/replaced/g' /tmp/dummy

Sed replaces the string 'tobereplaced' with the string 'replaced' and reads Irom the
/tmp/dummy Iile. The result will be sent to stdout (normally the console) but you can
also add '~ capture' to the end oI the line above so that sed sends the output to the Iile
'capture'.
$sed 12, 18d /tmp/dummy

Sed shows all lines except lines 12 to 18. The original Iile is not altered by this
command.
awk (manipulation oI dataIiles, text retrieval and processing)
Many implementations oI the AWK programming language exist (most known
interpreters are GNU's gawk and 'new awk' mawk.) The principle is simple: AWK
scans Ior a pattern, and Ior every matching pattern a action will be perIormed.
Again, I've created a dummy Iile containing the Iollowing lines:
test123
test
tteesstt
$awk '/test/ ,print,' /tmp/dummy

test123
test
The pattern AWK looks Ior is 'test' and the action it perIorms when it Iound a line in
the Iile /tmp/dummy with the string 'test' is 'print'.
$awk '/test/ ,i=i+1, END ,print i,' /tmp/dummy

3
When you're searching Ior many patterns, you should replace the text between the
quotes with '-I Iile.awk' so you can put all patterns and actions in 'Iile.awk'.
grep (print lines matching a search pattern)
We've already seen quite a Iew grep commands in the previous chapters, that display
the lines matching a pattern. But grep can do more.
$grep "look for this" /var/log/messages -c

12
The string "look Ior this" has been Iound 12 times in the Iile /var/log/messages.
|ok, this example was a Iake, the /var/log/messages was tweaked :-)|
wc (counts lines, words and bytes)
In the Iollowing example, we see that the output is not what we expected. The dummy
Iile, as used in this example, contains the Iollowing text: bash introduction howto test
file
$wc --words --lines --bytes /tmp/dummy

2 5 34 /tmp/dummy
Wc doesn't care about the parameter order. Wc always prints them in a standard order,
which is, as you can see: .
sort (sort lines oI text Iiles)
This time the dummy Iile contains the Iollowing text:
b
c
a
$sort /tmp/dummy

This is what the output looks like:
a
b
c
Commands shouldn't be that easy :-) bc (a calculator programming language)
Bc is accepting calculations Irom command line (input Irom Iile. not Irom redirector
or pipe), but also Irom a user interIace. The Iollowing demonstration shows some oI
the commands. Note that
I start bc using the -q parameter to avoid a welcome message.
$bc -q

1 5

.5 .5
1
5 ' 5

2 8
256
sqrt(9)
3
while (i ' 9) ]
i i 1,
print i
}
123456789
quit
tput (initialize a terminal or query terminIo database)
A little demonstration oI tput's capabilities:
$tput cup 10 4

The prompt appears at (y10,x4).
$tput reset

Clears screen and prompt appears at (y1,x1). Note that (y0,x0) is the upper leIt corner.
$tput cols

8
Shows the number oI characters possible in x direction.
It it higly recommended to be Iamiliarized with these programs (at least). There are
tons oI little programs that will let you do real magic on the command line.
|some samples are taken Irom man pages or FAQs|
2 More Scripts
2 Applying a command to all files in a directory
22 Sample: A very simple backup script (little bit better)
#!/bin/bash
SRCD="/home/"
TGTD="/var/backups/"
JF=home-$(date +%Y%m%d).tgz
tar -cZf $TGTD$JF $SRCD

23 File re-namer

#!/bin/sh
# renna: rename multiple files according to several rules
# written by felix hudson Jan - 2000

#first check for the various 'modes' that this program has
#if the first ($1) condition matches then we execute that
portion of the
#program and then exit

# check for the prefix condition
if $1 = p ,; then

#we now get rid of the mode ($1) variable and prefix ($2)
prefix=$2 ; shift ; shift

# a quick check to see if any files were given
# if none then its better not to do anything than rename some
non-existent
# files!!

if $1 = ,; then
echo "no files given"
exit 0
fi

# this for loop iterates through all of the files that we gave
the program
# it does one rename per file given
for file in $
do
mv $,file, $prefix$file
done

#we now exit the program
exit 0
fi

# check for a suffix rename
# the rest of this part is virtually identical to the previous
section
# please see those notes
if $1 = s ,; then
suffix=$2 ; shift ; shift

if $1 = ,; then
echo "no files given"
exit 0
fi

for file in $
do
mv $,file, $file$suffix
done

exit 0
fi

# check for the replacement rename
if $1 = r ,; then

shift

# i included this bit as to not damage any files if the user
does not specify
# anything to be done
# just a safety measure

if $# -lt 3 , ; then
echo "usage: renna r expression, replacement, files... "
exit 0
fi

# remove other information
JLD=$1 ; NEW=$2 ; shift ; shift

# this for loop iterates through all of the files that we give
the program
# it does one rename per file given using the program 'sed'
# this is a sinple command line program that parses standard
input and
# replaces a set expression with a give string
# here we pass it the file name ( as standard input) and replace
the nessesary
# text

for file in $
do
new=`echo $,file, | sed s/$,JLD,/$,NEW,/g`
mv $,file, $new
done
exit 0
fi

# if we have reached here then nothing proper was passed to the
program
# so we tell the user how to use it
echo "usage;"
echo " renna p prefix, files.."
echo " renna s suffix, files.."
echo " renna r expression, replacement, files.."
exit 0

# done!


24 File renamer (simple)
#!/bin/bash
# renames.sh
# basic file renamer

criteria=$1
re_match=$2
replace=$3

for i in $( ls $criteria );
do
src=$i
tgt=$(echo $i | sed -e "s/$re_match/$replace/")
mv $src $tgt
done
3 When something goes wrong (debugging)
3 Ways Calling BASH
A nice thing to do is to add on the Iirst line
#!/bin/bash -x

This will produce some intresting output inIormation
4 About the document
Feel Iree to make suggestions/corrections, or whatever you think it would be
interesting to see in this document. I'll try to update it as soon as I can.
4 (no) warranty
This documents comes with no warranty oI any kind. and all that
42 Translations
Italian: by William GhelIi (wizzy at tiscalinet.it) is here
French: by Laurent Martelli is missed
Korean: Minseok Park http://kldp.org
Korean: Chun Hye Jin unknown
Spanish: unknow http://www.insIlug.org
I guess there are more translations, but I don't have any inIo oI them, iI you have it,
please, mail it to me so I update this section.
43 Thanks to
O People who translated this document to other languages (previous section).
O Nathan Hurst Ior sending a lot oI corrections.
O Jon Abbott Ior sending comments about evaluating arithmetic expressions.
O Felix Hudson Ior writing the renna script
O Kees van den Broek (Ior sending many corrections, re-writting useIull comands
section)
O Mike (pink) made some suggestions about locating bash and testing Iiles
O Fiesh make a nice suggestion Ior the loops section.
O Lion suggested to mention a common error (./hello.sh: Command not Iound.)
O Andreas Beck made several corrections and coments.
44 History
New translations included and minor correcitons.
Added the section useIull commands re-writen by Kess.
More corrections and suggestions incorporated.
Samples added on string comparison.
v0.8 droped the versioning, I guess the date is enought.
v0.7 More corrections and some old TO-DO sections written.
v0.6 Minor corrections.
v0.5 Added the redirection section.
v0.4 disapperd Irom its location due to my ex-boss and thid doc Iound it's new place
at the proper url: www.linuxdoc.org.
prior: I don't rememeber and I didn't use rcs nor cvs :(
45 More resources
Introduction to bash (under BE) http://org.laol.net/lamug/beIorever/bashtut.htm
Bourne Shell Programming http://207.213.123.70/book/
Vim Color Editor HOW-TO (Vi Improved
with syntax color highlighting)
Al Dev (Alavoor Vasudevan) alavooryahoocom
v172 28 !une 2001

1bls Jocomeot ls o qolJe to polckly settloq op tbe vlm colot eJltot oo lloox ot uolx
systems 1be lofotmotloo bete wlll lmptove tbe ptoJoctlvlty of ptoqtommets becoose
tbe vlm eJltot soppotts syotox colot blqbllqbtloq ooJ bolJ foots lmptovloq tbe
teoJoblllty of ptoqtom coJe A ptoqtommets ptoJoctlvlty lmptoves 2 to J tlmes
wltb o colot eJltot llke vlm 1be lofotmotloo lo tbls Jocomeot opplles to oll opetotloq
sytems wbete vlm wotks socb os lloox wloJows 95/N1 Apple Moc l8M O5es vM5
8eO5 ooJ oll flovots of uolx llke 5olotls nlu\ Al\ 5cO 5lolx 85u ulttlx etc (lt
meoos olmost oll opetotloq systems oo tbls plooet!)

Introduction
O 11 8efore you lnsLall
O 12 lnsLall vlm on 8edhaL Llnux
O 13 lnsLall vlm on Cnu ueblan Llnux
O 14 lnsLall vlm on unlxes
O 13 lnsLall vlm on MlcrosofL Wlndows 93/n1
O 16 lnsLall vlm on vMS
O 17 lnsLall vlm on CS/2
O 18 lnsLall vlm on Apple MaclnLosh
2 Install Vim on Microsoft Windows 95/NT
O 21 lnsLall bash shell
O 22 LdlL bash_proflle
O 23 SeLup Wlndow colors
3 Setup gvim init files
O 31 Sample gvlmrc flle
O 32 xdefaulLs parameLers
4 Color Syntax init files
O 41 AuLo sourceln meLhod
O 42 Manual meLhod
5 VIM Usage
6 Vi companions
O 61 CLags for LSCL
O 62 CLags for !avaScrlpL programs korn 8ourne shells
O 63 uebugger gdb
7 Online VIM help
8 Vim Home page and Vim links
9 Vim Tutorial
O 91 vlm Pandson 1uLorlal
O 92 vl 1uLorlals on lnLerneL
Vi Tutorial
O 101 Cursor MovemenL Commands
O 102 8epeaL CounLs
O 103 ueleLlng 1exL
O 104 Changlng 1exL
O 103 ?anklng (Copylng) 1exL
O 106 lllLerlng LexL
O 107 Marklng Llnes and CharacLers
O 108 namlng 8uffers
O 109 SubsLlLuLlons
O 1010 Mlscellaneous Colon Commands
O 1011 SeLLlng CpLlons
O 1012 key Mapplngs
O 1013 LdlLlng MulLlple llles
O 1014 llnal 8emarks
Vim Reference Card
O 111 vl sLaLes
O 112 Shell Commands
O 113 SeLLlng CpLlons
O 114 noLaLlons used
O 113 lnLerrupLlng cancelllng
O 116 llle ManlpulaLlon
O 117 MovemenL
O 118 Llne oslLlonlng
O 119 CharacLer poslLlonlng
O 1110 Words senLences paragraphs
O 1111 Marklng and reLurnlng
O 1112 CorrecLlons durlng lnserL
O 1113 Ad[usLlng Lhe screen
O 1114 ueleLe
O 1113 lnserL change
O 1116 Copy and asLe
O 1117 CperaLors (use double Lo affecL llnes)
O 1118 Search and replace
O 1119 Ceneral
O 1120 Llne LdlLor Commands
O 1121 CLher commands
2 Related URLs
3 Other Formats of this Document
O 131 AcrobaL ul formaL
O 132 ConverL Llnuxdoc Lo uocbook formaL
O 133 ConverL Lo MS WlnPelp formaL
O 134 8eadlng varlous formaLs
4 Copyright Notice
Introduction
Vim stands Ior 'Vi Improved'. Vi is the most popular and powerIul editors in the Unix
world. Vi is an abbreviation Ior "Jisual" editor. One oI the Iirst editors was a line
editor called 'ed' (and 'ex'). The Jisual editor like Vi was a vast improvement over line
editors like 'ed' (or 'ex'). The editors 'ed' and 'ex' are still available on Linux: see 'man
ed' and 'man ex'.
A good editor improves programmer productivity. Vim supports color syntax
highlighting oI program code and also emphasises text using diIIerent Ionts like
normal, bold or italics. A color editor like Vim can improve the productivity oI
programmers by 2 to 3 times!! Programmers can read the code much more rapidly as
the code syntax is colored and highlighted.
Before you Install
BeIore you install Vim, please reIer to the OS speciIic release notes and inIormation
about compiling and usage oI Vim at -
O Co Lo Lhls locaLlon and look for flles os_*LxL hLLp//cvsvlmorg/cgl
bln/cvsweb/vlm/runLlme/doc
lf you do noL have Lhe vlm package (8M uL8 Lar zlp) Lhen download Lhe vlm
source code by fLp from Lhe offlclal vlm slLe
O 1he home page of vlm ls aL hLLp//wwwvlmorg
O Mlrror slLe ln uS ls aL hLLp//wwwusvlmorg
O lLp slLe fLp//fLpvlmorg/pub/vlm
O Cr use one of Lhe mlrrors fLp//fLpvlmorg/pub/vlm/Ml88C8S
2 Install Vim on Redhat Linux
To use Vim install the Iollowing RPM packages on Redhat Linux -

rpm -i vim.rpm
JR do this -
rpm -i vim-enhanced.rpm
rpm -i vim-X11.rpm
rpm -i vim-common.rpm
rpm -i vim-minimal.rpm

?ou can see Lhe llsL of flles Lhe vlm rpm lnsLalls by

rpm -qa | grep ^vim | xargs rpm -ql | less
or
rpm -qa | grep ^vim | awk ',print "rpm -ql " $1 ,' | /bin/sh | less

and browse ouLpuL uslng [k C18L+f C18L+u C18L+8 C18L+u or uslng arrow keys
page up/down keys See man less
Note that the RPM packages Ior Redhat Linux use a MotiI interIace. II you have
installed the GTK libraries on your system, consider compiling Vim Irom the source
code Ior a clean GUI interIace. For inIormation on compiling Vim Irom the source
code, see "Install Vim on Unixes", below.
3 Install Vim on GNU Debian Linux
To install Vim on Debian Linux (GNU Linux), login as root and when connected to
internet type -

apt-get install vim vim-rt

lL wlll download Lhe laLesL verslon of vlm lnsLall lL conflgure lL 1he flrsL package
llsLed ls vlm Lhe sLandard edlLor complled wlLh x11 supporL vlmrL ls Lhe vlm
runLlme lL holds all Lhe synLax and help flles
4 Install Vim on Unixes
For other Ilavors oI unixes like Solaris, HPUX, AIX, Sinix, SCO download the source
code Iile ( see BeIore you Install )


zcat vim.tar.gz | tar -xvf -
cd vim-5.5/src
./configure --enable-gui=motif
make
make install

5 Install Vim on Microsoft Windows 95/NT
See Install on MS Windows.
6 Install Vim on VMS
Download files
ou will need both the Unix and Extra archives to build vim.exe Ior VMS. For using
Vim's Iull power you will need the runtime Iiles as well. Get these Iiles ( see BeIore
you Install )
ou can download precompiled executables Irom: http://www.polarIox.com/vim
VMS vim authors are -
O zolLanarpadffy[essneLse
O arpadffy[alLavlsLaneL
O cec[gryphongsfcnasagov
O 8nPunsaker[chqbyuedu
O sandorkopanyl[alLavlsLaneL
ompiling
Unpack the Unix and Extra archives together into one directory. In the .SRC~
subdirectory you should Iind the make Iile OSVMS.MMS. By editing this Iile you
may choose between building the character, GUI and debug version. There are also
additional options Ior Perl, Python and Tcl support.
ou will need either the DECSET mms utility or the Ireely available clone oI it called
mmk (VMS has no make utility in the standard distribution). ou can download mmk
Irom http://www.openvms.digital.com/Ireeware/MMK/
II you have MSS on your system, the command
~ mms /descriposvms.mms
will start building your own customised version oI Vim. The equivalent command Ior
mmk is:
~ mmk /descriposvms.mms
Deploy
Vim uses a special directory structure to hold the document and runtime Iiles:

vim (or wherever)
|- tmp
|- vim55
|----- doc
|----- syntax
|- vim56
|----- doc
|----- syntax
vimrc (system rc files)
gvimrc

Use:

define/nolog device:leading-path-here.vim, vim
define/nolog device:leading-path-here.vim.vim56, vimruntime
define/nolog device:leading-path-here.tmp, tmp

to get vim.exe to Iind its document, Iiletype, and syntax Iiles, and to speciIy a
directory where temporary Iiles will be located. Copy the "runtime" subdirectory oI
the vim distribution to vimruntime.
Note: Logicals $VIMRUNTIME and $TMP are optional. Read more at :help runtime
^actical usage
Usually you want to run just one version oI Vim on your system, thereIore it is
enough to dedicate one directory Ior Vim. Copy all Vim runtime directory structure to
the deployment position. Add the Iollowing lines to your LOGIN.COM (in
SS$LOGIN directory). Set up logical $VIM as:

$ define VIM device: <path

Set up some symbols:

$ ! vi starts Vim in chr. mode.
$ vim :== mcr device:<pathVIM.EXE

$ !gvi starts Vim in GUI mode.
$ gvim :== spawn/nowait mcr device:<pathVIM.EXE -g

Create .vimrc and .gvimrc Iiles in your home directory (SS$LOGIN).
The easiest way is just rename example Iiles. ou may leave the menu Iile
(MENU.VIM) and Iiles vimrc and gvimrc in the original $VIM directory. It will be
deIault setup Ior all users, and Ior users is enough just to have their own additions or
resetting in home directory in Iiles .vimrc and .gvimrc. It should work without
problems.
Note: Remember, system rc Iiles (deIault Ior all users) do not have the leading "." So,
system rc Iiles are:

VIM$:vimrc
VIM$:gvimrc
VIM$:menu.vim

and users cusLomlsed rc flles are

sys$login:.vimrc
sys$login:.gvimrc

ou can check that everything is on the right place with the :version command.

Example LJGIN.CJM:

$ define/nolog VIM RF10:UTIL.VIM,
$ vim :== mcr VIM:VIM.EXE
$ gvim :== spawn/nowait mcr VIM:VIM.EXE -g
$ set disp/create/node=192.168.5.223/trans=tcpip

Note: This set-up should be enough iI you are working in a standalone server or
clustered environment, but iI you want to use Vim as an internode editor, it should
suIIice. ou just have to deIine the "whole" path:

$ define VIM "<server_name""user password"",::device:<path"
$ vim :== "mcr VIM:VIM.EXE"

as Ior example:

$ define VIM "PLUTJ::RF10:UTIL.VIM,"
$ define VIM "PLUTJ""ZAY mypass""::RF10:UTIL.VIM," ! if passwd
required

ou can also use $VIMRUNTIME logical to point to proper version oI Vim iI you
have multiple versions installed at the same time. II $VIMRUNTIME is not deIined
Vim will borrow value Irom $VIM logical. ou can Iind more inIormation about
$VIMRUNTIME logical by typing :help runtime as a Vim command.
mode questions
VMS is not a native X window environment, so you can not start Vim in GUI mode
"just like that". But it is not too complicated to get a running Vim.

1) If you are working on the VMS X console:
Start Vim with the command:

$ mc device:<pathVIM.EXE -g

or type :gui as a command to the Vim command prompt. For more info :help
gui

2) If you are working on other X window environment as Unix or some remote X
VMS console. Set up display to your host with:

$ set disp/create/node=<your IP address/trans=<transport-name

and start Vim as in point 1. You can find more help in VMS documentation
or
type: help set disp in VMS prompt.
Examples:

$ set disp/create/node=192.168.5.159 ! default trans is
DECnet
$ set disp/create/node=192.168.5.159/trans=tcpip ! TCP/IP network
$ set disp/create/node=192.168.5.159/trans=local ! display on the
same node

Note: you should deIine just one oI these. For more inIormation type $help set disp in
VMS prompt.
7 Install Vim on OS/2
Read the release notes Ior Vim on OS/2, see BeIore you Install .
At present there is no native PM version oI the GUI version oI vim: The OS/2 version
is a console application. However, there is now a Win32s-compatible GUI version,
which should be usable by owners oI Warp 4 (which supports Win32s) in a Win-OS/2
session. The notes in this Iile reIer to the native console version.
To run Vim, you need the emx runtime environment (at least rev. 0.9b). This is
generally available as (ask Archie about it):

emxrt.zip emx runtime package

8 Install Vim on Apple Macintosh
Read the release notes Ior Vim on OS/2, see BeIore you Install .
The author oI Vim on Mac (old version vim 3.0) is

Eric Fischer
5759 N. Guilford Ave
Indianapolis IN 46220 USA

Lmall Lo enf[poboxcom
Mac Bug Report When reporting any Mac speciIic bug or Ieature change, makes sure
to include the Iollowing address in the "To:" or "Copy To:" Iield.
dany.stamantsympatico.ca
Vim compiles out oI the box with the supplied CodeWarrior project when using
CodeWarrior 9. II you are using a more recent version (e. g. CW Pro) you have to
convert the project Iirst. When compiling Vim Ior 68k Macs you have to open the
"size" resource in ResEdit and enable the "High level events aware" button to get drag
and drop working. ou have to increase the memory partition to at least 1024 kBytes
to prevent Vim Irom crashing due to low memory.

vim:ts=8:sw=8:tw=78:
2 Install Vim on Microsoft Windows 95/NT
For Windows 95/NT, download the Vim zip Iile. For Windows 95/NT you must
download TWO zip Iiles -
O 8unLlme supporL flle v|m*rtz|p
O vlm command flle v|m*S6z|p Where vlm verslon ls 36
Get these two zip Iiles ( see BeIore you Install ) Unpack the zip Iiles using the
Winzip http://www.winzip.com. Both the zip Iiles (vim*rt.zip and vim*56.zip) must
be unpacked in the same directory like say c:\vim.
For Windows 95/98, set the environment variable VIM in autoexec.bat by adding this
line -

set VIM=c:\vim\vim56

lor Wlndows n1 add Lhe envlronmenL varlable vlM Lo Lhe Contro| ane| | System |
Lnv|ronment | System ropert|es dlalog

VIM=c:\vim\vim56

The VIM variable should point to whereever you installed the vim56 directory. ou
can also set your PATH to include the gvim.exe's path.
ou may need to logoII and relogin to set your environment. At an MS-DOS prompt
type -

set vim

And you should see vlMcvlmvlm36
Create a short-cut on to your desktop by click-and-drag Irom c:\vim\vim56\gvim.exe.
Copy the gvimrcexample Iile to the $VIM\gvimrc. In my case it is
c:\vim\vim56\gvimrc.

copy c:\vim\vim56\gvimrc_example $VIM\_gvimrc

2 Install bash shell
In order make MS Windows 2000/NT/95/98 even more user-Iriendly, install the bash
shell (Bourne Again Shell).
Installhttp://sources.redhat.com/cygwin/setup.exe (Cygwin-setup program) and select
bash and other common utilities. The CygWin main site is
athttp://sources.redhat.com/cygwin. With CygWin the Windows 2000 computer will
look like Linux/Unix box!! And combined with gvim editor, the Windows 2000 gives
programmers more power.
22 Edit bash_profile
AIter installing the Cygwin, insert some useIul aliases in /.bashproIile Iile. Open a
cygwin window and at bash prompt -

bash$ cd $HJME
bash$ gvim .bash_profile
set -o vi
alias ls='ls --color '
alias cp='cp -i '
alias mv='mv -i '
alias rm='rm -i '
alias vi='gvim '
alias vip='gvim ~/.bash_profile & '
alias sop='. ~/.bash_profile '
alias mys='mysql -uroot -p '
PATH=$PATH:"/cygdrive/c/Program Files/mysql/bin"

WlLh color ls when you do ls you wlll see all Lhe dlrecLory names and flles ln
dlfferenL colors (lL looks greaL!!) WlLh seL o vl you can use Lhe command llne
hlsLory edlLlng [usL as ln llnux
23 Setup Window colors
The deIault background color oI MS DOS prompt window is black and white text.
ou must change the color, Iontsize and window size to make it more pleasing. On
MS Windows 2000, click on button Start-~Run and type "cmd" and hit return. On MS
Windows 95/98/NT click on Start-~Programs-~MSDOS Prompt which will bring up
MSDOS window. Right click on the top leIt corner oI the MSDOS prompt window
and select properties. Select color background and enter R255, G255, B190 (red,
green, blue) Ior lightyellow background and text Ioreground color to black (R0,
G0, B0). This sets background to light yellow and text Ioreground to black and this
combination is most pleasing to human eyes. II you have problems with colors in
cygwin bash window when doing 'man ls', set the text color to "marune".
For Windows95 see Color Ior MS-DOS prompt window.
3 Setup gvim init files
To enable the syntax color highlighting you MUST copy the gvimrc Iile to your home
directory. This will also put the "Syntax" Menu with gvim command. ou can click
on Syntax Menu and select appropriate languages like C, Perl, Java, SQL, ESQL
etc..

cd $HJME
cp /usr/doc/vim-common-5.3/gvimrc_example ~/.gvimrc

CommenL llnes ln gvlmrc begln wlLh doublequoLes () ?ou can cusLomlze gvlm by
edlLlng Lhe flle $PCML/gvlmrc and puL Lhe followlng llnes

" This line is a comment .... one which begins with double-quotes
" The best is the bold font, try all of these and pick one....
set guifont=8x13bold
"set guifont=9x15bold
"set guifont=7x14bold
"set guifont=7x13bold
"
" Highly recommended to set tab keys to 4 spaces
set tabstop=4
set shiftwidth=4
"
" The opposite is 'set wrapscan' while searching for strings....
set nowrapscan
"
" The opposite is set noignorecase
set ignorecase
set autoindent
"
" You may want to turn off the beep sounds (if you want quite) with visual
bell
" set vb

" Source in your custom filetypes as given below -
" so $HJME/vim/myfiletypes.vim

lL ls very strong|y recommended LhaL you seL Lhe tobstop Lo 4 and sblftwlJtb Lo 4
1he tobstop ls Lhe number of spaces Lhe 1A8 key wlll lndenL whlle edlLlng wlLh gvlm
1he sblftwlJtb ls Lhe number of spaces Lhe llnes wlll be shlfLed wlLh or vl
commands 8efer Lo vl LuLorlals vlm 1uLorlal for more deLalls
To see the list oI available Ionts on Linux/Unix see the command xlsfonts. Type -

bash$ xlsfonts | less
bash$ xlsfonts | grep -i bold | grep x
bash$ man xlsfonts

3 Sample gvimrc file
ou can change the settings like color, bold/normal Ionts in your $HOME/.gvimrc
Iile. It is very strongly recommended that you set the background color
tolightyellow or white with black Ioreground. Ergonomics says that best background
color is lightyellow or white with black Ioreground. Hence change the variable 'guibg'
in your $HOME/.gvimrc Iile as Iollows:

highlight Normal guibg=lightyellow

The sample gvimrc Irom /usr/doc/vim-common-5.3/gvimrcexample is as Iollows:

" Vim
" An example for a gvimrc file.
" The commands in this are executed when the GUI is started.
"
" To use it, copy it to
" for Unix and JS/2: ~/.gvimrc
" for Amiga: s:.gvimrc
" for MS-DJS and Win32: $VIM\_gvimrc

" Make external commands work through a pipe instead of a pseudo-tty
"set noguipty

" set the X11 font to use. See 'man xlsfonts' on unix/linux
" set guifont=-misc-fixed-medium-r-normal--14-130-75-75-c-70-iso8859-1
set guifont=8x13bold
"set guifont=9x15bold
"set guifont=7x14bold
"set guifont=7x13bold
"
" Highly recommended to set tab keys to 4 spaces
set tabstop=4
set shiftwidth=4
"
" The opposite is 'set wrapscan' while searching for strings....
set nowrapscan
"
" The opposite is set noignorecase
set ignorecase
"
" You may want to turn off the beep sounds (if you want quite) with visual
bell
" set vb

" Source in your custom filetypes as given below -
" so $HJME/vim/myfiletypes.vim

" Make command line two lines high
set ch=2

" Make shift-insert work like in Xterm
map <S-Insert <MiddleMouse
map! <S-Insert <MiddleMouse

" Jnly do this for Vim version 5.0 and later.
if version = 500

" I like highlighting strings inside C comments
let c_comment_strings=1

" Switch on syntax highlighting.
syntax on

" Switch on search pattern highlighting.
set hlsearch

" For Win32 version, have "K" lookup the keyword in a help file
"if has("win32")
" let winhelpfile='windows.hlp'
" map K :execute "!start winhlp32 -k <cword " . winhelpfile <CR
"endif

" Hide the mouse pointer while typing
set mousehide

" Set nice colors
" background for normal text is light grey
" Text below the last line is darker grey
" Cursor is green
" Constants are not underlined but have a slightly lighter background
highlight Normal guibg=grey90
highlight Cursor guibg=Green guifg=NJNE
highlight NonText guibg=grey80
highlight Constant gui=NJNE guibg=grey95
highlight Special gui=NJNE guibg=grey95

endif

See also sample vlmrc used for console mode vlm command from /usr/doc/vlm
common33/vlmrc_example
32 Xdefaults parameters
ou can set some oI the Vim properties in XdeIaults Iile.
WARNING: o not set Jimgeometry as it will break the gvim menu,
use Jim.geometry instead.
Edit the $HOME/.XdeIaults Iile and add the Iollowing lines:

! GVim great Colors.
VimuseSchemes: all
VimsgiMode: true
VimuseEnhancedFSB: true
Vim.foreground: Black
!Vim.background: lightyellow2
Vimbackground: white
! Do NJT use Vimgeometry , this will break the menus instead
! use Vim.geometry. Asterisk between Vim and geometry is not allowed.
! Vim.geometry: widthxheight
Vim.geometry: 88x40
!Vimfont: -misc-fixed-medium-r-normal--20-200-75-75-c-100-
iso8859-15-5
VimmenuBackground: yellow
VimmenuForeground: black

ln order for Lhls change Lo Lake effecL Lype

xrdb -merge $HJME/.Xdefaults
man xrdb

ou can also edit the ~/.gvimrc Iile to change the background colors

gvim $HJME/.gvimrc
The best background color is lightyellow or white, with black foreground.
highlight Normal guibg=lightyellow
4 Color Syntax init files
4 Auto source-in method
This section below is obtained Irom gvim session by typing 'help syntax' -

bash$ gvim some_test
:help syntax

Click on the menu Window~CloseOthers to close other Window. And then do
CTRL| on 'Syntax Loading Procedure' menu which will take you there. (Use
CTRLT to rewind and go back).
II a Iile type you want to use is not detected, then there are two ways to add
it. Method : ou can modiIy the $JIMRUNTIME/filetype.vim Iile, but this is not
recommended as it will be overwritten when you install a new version oI Vim.
Method 2: Create a Iile in $HOME/vim/myIiletypes.vim and put these lines in it -

"

" Filename : $HJME/vim/myfiletypes.vim
" See the document by typing :help autocmd within vim session
" see also the doc at /usr/share/vim/doc/autocmd.txt
" This file will setup the autocommands for new filetypes
" using the existing syntax-filetypes.
" For example when you open foo.prc it will use syntax of plsql
" Basically does :set filetype=prc inside vim
" Add a line in $HJME/.gvimrc as below:
" so $HJME/vim/myfiletypes.vim
"


augroup filetype
au!
au! BufRead,BufNewFile .phc set filetype=php
au! BufRead,BufNewFile .mine set filetype=mine
au! BufRead,BufNewFile .xyz set filetype=drawing
au! BufRead,BufNewFile .prc set filetype=plsql
augroup END

Then add a line in your $HOME/.vimrc and $HOME/.gvimrc Iile to source in the Iile
"myIiletypes.vim". (CAUTION: ou MUST put this in both vimrc and gvimrc Iiles
in order Ior this to work) Example:

so $HJME/vim/myfiletypes.vim

NOTE: Make sure that you set "so myIiletypes.vim" beIore switching on Iile type
detection. This is must be beIore any ":Iiletype on" or ":syntax on" command.
See the documentation on autocommand at -
O :help autocmd (within a vim editing session)
O See also the doc at /usr/share/vim/doc/autocmd.txt
our Iile will then be sourced in aIter the deIault FileType autocommands have been
installed. This allows you to overrule any oI the deIaults, by using ":au!" to remove
any existing FileType autocommands Ior the same pattern. Only the autocommand to
source the scripts.vim Iile is given later. This makes sure that your autocommands in
"myIiletypes.vim" are used beIore checking the contents oI the Iile.
42 Manual method
Instead oI using "Syntax" menu you can also manually source in the syntax Iile. Edit
the Iile with gvim and at : (colon) command give 'so' command. For example -

gvim foo.pc
:so $VIM/syntax/esqlc.vim

The syntax source Iiles are at /usr/share/vim/syntax/*.vim. Vim supports more than
120 diIIerent syntax Iiles Ior diIIerent languages like C, PERL, VHDL,
JavaScript,...and so on!!
Each syntax Iile supports one or more deIault Iile name extensions, Ior example,
JavaScript syntax Iile supports the *.js extension. II you happen to use an extension
that conIlicts with another deIault syntax Iile (such as adding JavaScript to a *.html
Iile) than you can source in the additional syntax Iile with the command :so
$VIM/syntax/javascript.vim. To avoid all oI this typing, you can create a soIt link like
-

ln -s $VIM/syntax/javascript.vim js
gvim foo.html (... this file contains javascript functions and HTML)
:so js
5 VIM Usage
ou can use Vim in two modes - one with GUI and other without GUI. To use GUI
use command -

gvim foo.cpp

To use non-gui mode give -

vim foo.cpp
JR plain vanilla mode
vi foo.cpp

It is very strongly recommended that you always use gvim instead oI vim, since GUI
mode with colors will deIinitely improve your productivity.
GUI mode gvim provides the Iollowing -
O ou can mark the text using the mouse to do cut, copy and paste.
O ou can use the Menu bar which has - File, Edit, Window, Tools, Synatx and
Help buttons.
O Also in near Iuture in gvim - a second menu bar will display the list oI Iiles
being edited, and you can switch Iiles by clicking on the Iilenames, until then
you can use vi commands - :e#, :e#1, :e#2, :e#3, :e#4, ....so on to select the
Iiles.
6 Vi companions
Generally Vim is used in conjunction with other powerIul tools
like ctags and gdb. ctags is Ior very rapid navigation through millions oI lines oI
"C/C" code and gdb is Ior debugging the "C/C" code. A brieI introduction oI
these two indispensable commands will be given in this chapter.
ctags is the most powerIul command available Ior coding C, C, Java, Perl,
Korn/Bourne shell scripts or Fortran. Developers very extensively use ctags to
navigate through thousands oI Iunctions within C/C programs. See 'man ctags' on
Unix. It is very important that you learn how to use ctags to develop programs in C
or C, Java, etc.. Navigation is the single most important task while doing
development oI C or C code. Using ctags you can very quickly read the code by
jumping Irom a calling line to the called Iunction, drill down deeper into nested
Iunction calls, and unwind back all the way up to the top. ou can go back and Iorth
Irom Iunction to Iunction very quickly.
Without NAVIGATION you will be completely lost! ctags is like the magnetic
COMPASS needle Ior the programmers.
Usage oI ctags :

ctags .cpp
gvim -t foo_function
gvim -t main

1hls wlll edlL Lhe C++ program flle whlch conLalns Lhe funcLlon foo_funcLlon() and wlll
auLomaLlcally place Lhe cursor on Lhe flrsL llne of Lhe funcLlon foo_funcLlon() 1he
second command Lakes you Lo Lhe llne wlLh Lhe maln() funcLlon deflnlLlon
Inside the Vim editor, you can jump to a Iunction by typing : (colon) tag Iunction
name ~as below -

:tag sample_function

1hls wlll place Lhe cursor on flrsL llne of sample_funcLlon()
II you want to jump into the Iunction Irom a line in Iile which contains the Iunction
name, place the cursor just beIore the Iunction name and press CTRL+](press control
key and leIt-square-bracket key simultaneously).

// example code
switch(id_number) ,
Case 1:
if ( foo_function( 22, "abcef") == 3 )
^
|
|
|
Place the cursor here (just before foo_function) and press
CTRL+,
This takes you to the function named "foo_function".
To come back to this line press CTRL+t

1o go back Lo Lhe calllng llne press C1kL+t (ConLrol key and leLLer L LogeLher) keep
presslng C1kL+t Lo unwlnd and go Lo Lhe flrsL llne where you sLarLed Lhe navlgaLlon
1haL ls you can keep presslng C1kL+ and Lhen keep presslng C1kL+t Lo go back ?ou
can repeaL Lhese as many Llmes as you wanL Lo have compleLe navlgaLlon Lhrough all
Lhe funcLlons of C or C++
6 Ctags for ESQL
Since ctags does not directly support the Embedded SQL/C (ESQL) language, the
Iollowing shell script can be used to create tags Ior esql. ESQL/C is database SQL
commands embedded inside the "C" programs. Oracle's ESQL/C is called Pro*C and
Sybase, InIormix have ESQL/C and PostgreSQL has product "ecpg".
Save this Iile as "sqltags.sh" and do chmod arx tagsgen.sh.

#!/bin/sh

# Program to create ctags for ESQL, C++ and C files
ESQL_EXTN=pc
tag_file1=tags_file.1
tag_file2=tags_file.2

which_tag=ctags

rm -f $tag_file1 $tag_file2 tags

aa=`ls .$ESQL_EXTN`
#echo $aa
for ii in $aa
do
#echo $ii
jj=`echo $ii | cut -d'.' -f1`
#echo $jj

if ! -f $jj.cpp ,; then
echo " "
echo " "
echo ""
echo "ESQL .cpp files does not exist.. "
echo "You must generate the .cpp from .pc file"
echo "using the Jracle ProC pre-compiler or Sybase"
echo "or Informix esql/c pre-compiler."
echo "And then re-run this command"
echo ""
echo " "
exit
fi

rm -f tags
$which_tag $jj.cpp
kk=s/$jj\.cpp/$jj\.pc/g

#echo $kk sed.tmp
#sed -f sed.tmp tags $tag_file1

#sed -e's/sample\.cpp/sample\.pc/g' tags $tag_file1
sed -e $kk tags $tag_file1
done

# Now handle all the C++/C files - exclude the ESQL .cpp files
rm -f tags $tag_file2
bb=`ls .cpp .c`
aa=`ls .$ESQL_EXTN`
for mm in $bb
do
ee=`echo $mm | cut -d'.' -f1`
file_type="NJT_ESQL"
# Exclude the ESQL .cpp and .c files
for nn in $aa
do
dd=`echo $nn | cut -d'.' -f1`
if "$dd" = "$ee" ,; then
file_type="ESQL"
break
fi
done

if "$file_type" = "ESQL" ,; then
continue
fi

rm -f tags
$which_tag $mm
cat tags $tag_file2
done

mv -f $tag_file2 tags
cat $tag_file1 tags
rm -f $tag_file1

# Must sort tags file for it work properly ....
sort tags $tag_file1
mv $tag_file1 tags

62 Ctags for 1avaScript programs, Korn, Bourne shells
The shell script given below can be used to generate tags Ior a very large variety oI
programs written in JavaScript, PHP/FI scripts, Korn shell, C shell, Bourne shell and
many others. This is a very generic module.
Save this Iile as tagsgen.sh and do chmod arx tagsgen.sh.

#!/bin/sh

tmp_tag=tags_file
tmp_tag2=tags_file2

echo " "
echo " "
echo " "
echo " "
echo " "
echo "Generate tags for ...."
while :
do
echo " Enter file extension for which you want to generate tags."
echo -n " File-extension should be like sh, js, ksh, etc... : "
read ans

if "$ans" == "" ,; then
echo " "
echo "Wrong entry. Try again!"
else
break
fi
done

\rm -f $tmp_tag

aa=`ls .$ans`

for ii in $aa
do
jj=`echo $ii | cut -d'.' -f1`
#echo $jj
cp $ii $jj.c
ctags $jj.c
echo "s/$jj.c/$ii/g" $tmp_tag2
sed -f $tmp_tag2 tags $tmp_tag
\rm -f tags $jj.c
done

sort $tmp_tag tags

\rm -f $tmp_tag $tmp_tag2

63 Debugger gdb
ou would be using gdb extensively along with Vi. Debugging is the most important
aspect oI programming as the major cost oI soItware projects goes into debugging and
testing.
To debug C/C programs use 'gdb' tool. See 'man gdb'. ou must compile your
programs with -g3 option like
gcc -g3 foo.c foo_another.c sample.c
To set up easy aliases do -
Setup an alias in your ~/.bash_profile
alias gdb='gdb -directory=/home/src -directory=/usr/myname/src '
Give -
gdb foo.cpp
gdb dir /hom2/another_src
This will add to file search path
gdb break 'some_class::func<TAB<TAB
This will complete the function name saving you typing time... and will
output like -
gdb break 'some_class::function_foo_some_where(int aa, float bb)'
Pressing TAB key twice is the command line completion, which will save you lots oI
typing time. This is one oI the most important technique oI using gdb.
To get online help do -
gdb help
Gives online help
gdb help breakpoints
Gives more details about breakpoints.
To set breakpoints and do debugging
unixprompt gdb exe_filename
gdb b main
This will put breakpoint in main() function
gdb b 123
This will put breakpoint in line 123 of the current file
gdb help breakpoints
Gives more details about breakpoints.
To analyze the core dumps do
unixprompt gdb exe_filename core
gdb bt
Gives backtrace of functions and line numbers where the program failed
gdb help backtrace
Gives more details about backtrace.
ou can also use GUI version oI gdb called xxgdb.
See also gdb interIace to Vim at http://www.lxlinux.com/gdbvim.tgz.
Memory leak tools -
O lreeware LlecLrlc lence on llnux cd
O Commerclal Lools urlfy hLLp//wwwraLlonalcom
O lnsure++ hLLp//wwwlnsurecom
7 Online VIM help
See the online man pages. At unix shell prompt type 'man vim' and 'man gvim'.
Or inside the gvim session type :help to get the help page. See also Vim Tutorial To
see the settings type :set all or :set. To see list oI options type :options. To see topics
on set type :help set.
VIM - main help file

Move around: Use the cursor keys, or "h" to go left,
"j" to go down, "k" to go up, "l" to go right.
":1" takes you to 1st line of page
":n" takes you to nth line of page
"<SHIFTg" takes you to bottom of page
":/someword/ will search for "someword" in doc

Close this window: Use ":q<Enter".

Jump to a subject: Position the cursor on a tag between |bars| and hit CTRL-
,.

With the mouse: ":set mouse=a" to enable the mouse (in xterm or GUI).
Double-click the left mouse button on a tag between
|bars|.

jump back: Type CTRL-T or CTRL-J.

Get specific help: It is possible to go directly to whatever you want help
on, by giving an argument to the ":help" command |:help|.
It is possible to further specify the context:
WHAT PREPEND EXAMPLE ~
Normal mode commands (nothing) :help x
Visual mode commands v_ :help v_u
Insert mode commands i_ :help i_<Esc
command-line commands : :help :quit
command-line editing c_ :help c_<Del
Vim command arguments - :help -r
options ' :help 'textwidth'

list of documentation files:

|howto.txt| how to do the most common things
|intro.txt| introduction to Vim
|index.txt| alphabetical index for each mode
|autocmd.txt| automatically executing commands on an event
|change.txt| delete and replace text
8 Vim Home page and Vim links
The home page oI vim is at http://www.vim.org and mirror site in US is
at http://www.us.vim.org
Vim FAQ is at http://www.graInetix.com/~laurent/vim/Iaq.html and
at http://www.vim.org/Iaq
Eli's Vim Page at http://www.netusa.net/~eli/src/vim.html
The Vi Lovers Home Page http://www.cs.vu.nl/~tmgil/vi.html
Vim ReIerence Guide at http://scisun.sci.ccny.cuny.edu/~olrcc/vim/
Vim mailing list
at http://www.Iindmail.com/listsaver/vimannounce.html and http://www.vim.org/mail
.html
Mailing list archives are kept at:
O hLLp//wwwegroupscom/group/vlm
O hLLp//wwwegroupscom/group/vlmdev
O hLLp//wwwegroupscom/group/vlmannounce
Vim macros http://www.graInetix.com/~laurent/vim/macros.html
9 Vim Tutorial
9 Vim Hands-on Tutorial
On Linux system see the tutorial at /usr/doc/vim-common-5.*/tutor, on other unix
systems go to directory where vim is installed and look Ior doc directory.

bash$ cd /usr/doc/vim-common/tutor
bash$ less README.txt
bash$ cp tutor $HJME
bash$ cd $HJME
bash$ less tutor

92 Vi Tutorials on Internet
O urdue unlverslLy hLLp//ecnwwwecnpurdueedu/LCn/uocumenLs/vl/
O Culck vl LuLorlal hLLp//llnuxwwwdberauedu/LuC/node163hLml
O Advanced vl LuLorlal hLLp//wwwyggdrasllcom/blble/blblesrc/useralpha
4/gulde/node171hLml
O 1uLorlals hLLp//wwwcfmbrownedu/unlxhelp/vl_hLml
O 1uLorlals hLLp//wwwllnuxboxcom/Laylor/4lLrwrd/secLlon3_4hLml
O unlx world onllne vl
LuLorlal hLLp//wwwneLworkcompuLlngcom/unlxworld/unlxhomehLml
O unlv of Pawall LuLorlal hLLp//wwwenghawalledu/1uLor/vlhLml
O lnfo8ound hLLp//wwwlnfoboundcom/vlhLml
O Cornell unlv hLLp//wwwLccornelledu/Ldu/1uLor/8aslcs/vl/
O vl Lovers home page hLLp//wwwcsvunl/Lmgll/vlhLml
O AfLer SepL 2000 wlll moveLo hLLp//wwwLhomercom/Lhomer/vl/vlhLml
O 8eglnners Culde Lo
vl hLLp//wwwcsumredu/unlxlnfo/general/packages/vlguldehLml
O vl Pelp flle hLLp//wwwvmunlxcom/gabor/vlhLml
O vlm lAC hLLp//wwwmaLhfuberllnde/guckes/vlm/faq/
1here are many vl 1uLorlals on lnLerneL ln ?ahoo (Lycos exclLe or PoLboL) enLer vl
1uLorlal ln search fleld and search englne wlll reLurn many polnLers
Vi Tutorial
In this tutorial, we describe some "advanced" vi concepts and commands, so you can
appreciate the power oI vi and so you decide how to build your knowledge
oI vi commands. Nearly all vi reIerences list the available commands, but many don't
bother to discuss how the commands interrelate; this topic is the main purpose oI this
tutorial.
Cursor Movement Commands
The vi cursor movement commands allow you to position the cursor in the Iile and/or
on the screen eIIiciently, with a minimum number oI keystrokes. There are oodles oI
cursor movement commands - don't try memorizing them all at once! Later, we'll see
that much oI the power oI vi comes Irom mixing cursor movement commands with
other commands to delete, change, yank (copy), and Iilter text.
Please edit a large text Iile (say, wknight) so you can experiment with each command
as it is described. Keep in mind these commands will only work in Command Mode,
not Insert Mode; iI you start getting your "commands" in your text, press the ESC key
to return to Command Mode.
O cursor keys : As we've seen, cursor keys move by single character amounts
leIt, down, up, and right. Movement above the top oI the Iile, below the bottom,
to the right oI the end oI a line, or leIt oI the beginning is not allowed (no line
wrapping).
O hjkl : When vi was written (around 1978), many terminals on UNIX systems
did not have cursor keys! h, j, k, and l were chosen as commands to move leIt,
down, up, and right, respectively. Try them! Most vi diehards preIer these to
the cursor keys because
o (a) they are in the same place on all keyborads, and
o (b) they Iit nicely under the Iingers, unlike most cursor keys, which are
arranged in a box or "T" or some other nonlinear shape.
Why h, j, k, and l? Well, in the ASCII character set, CTRL-H is backspace
(moves leIt), CTRL-J is lineIeed (moves down), and, oI course, k and l are next
to h and j, so you see, they're mnemonic.
O : ("zero", not "oh") Move to the beginning oI current line. (To try this and the
next Iew commands, use the cursor keys or h j k l to move to an indented text
line that contains Iew "e" characters. II you can't Iind an indented line in your
Iile, create one by inserting a Iew space characters at the beginning oI a line.)
O ^ : Move to Iirst non-white character oI current line. (For indented line, 0 and `
are diIIerent.)
O $ : Move to last character oI current line.
O tC : Move to (but not on) next character c in current line. (Press 0, then press
te. This will move to the Iirst e in the curent line.)
O fC : Find (move on top oI) next character c in current line. (Press Ie, and the
cursor will Iind - that is, move on top - the next e in the current line.)
O TC : Move to (but not on) the previous character c in current line (Press $, then
Te.)
O FC : Find (move on top oI) the previous character c in current line. (Press Fe.)
O n[ : Move to column n in current line. (Try 20 ,. The digits 2 and 0 will not be
displayed as you type them, but when you press , the cursor will move to
column 20.) Try some experiments with t I T F , . When you do something
illegal, vi will beep your terminal.
O w : Forward to beginning oI next "small" word ( a "small" word consists oI
unbroken alphanumeric characters or punctuation characters, but not mixed
alphanumeric and punctuation). Try tapping w a dozen times or so - note what
happens at punctuation.
O W : Forward to beginning oI next "big" word (alphanumeric and punctuation
mixed). Try W a dozen times or so.
O b : Backward to beginning oI "small" word.
O B : Backward to beginning oI "big" word.
O e : Forward to end oI "small" word.
O E : Forward to end oI "big" word.
O + Return : Move to Iirst non-white space character on next line. ( and the
Return key have the same eIIect.)
O - : Move to Iirst non-white space character on previous line.
O ) : Move to the end oI sentence. (A sentence ends either at a blank line or at a
period or examination mark Iollowed by two space characters or at the end oI a
line. A period or exclamation mark Iollowed by one space character does not
end a sentence; this is correct behaviour, according to traditional rules oI how
sentences should appear in typed documents, but oIten appears wrong to those
who have never suIIered through a Iormal typing class.)
O ( : Move to beginning oI sentence.
O ] : Move to end oI paragraph. (Paragraphs are seperated with blank lines,
by vi's deIinition.)
O : Move to beginning oI paragraph.
O H : Move to home position (top line) on the screen
O M : Move to middle line on the screen.
O L : Move to last line on the screen.
O nG : Move to line n. II n is not given, move to the last line in the Iile. (Try 15G
to move to line 15, Ior example. The CTRL-G command displays the name oI
the Iile, some status inIormation, and the current line number. To move to the
top oI the Iile: 1G)
O CTRL-d : Scroll down halI-screen (see note).
O CTRL-u : Scroll up halI-screen (see note).
O CTRL-f : Move Iorward one-screen (see note).
O CTRL-b : Move backward one-screen (see note).
O Note : These Iour scrolling/paging commands cannot be used with the delete,
change, yank, or Iilter commands.
O /reg_exp : Move to next occurrence oI the regular expression regexp When
you press /, the cursor drops to the lower leIt corner oI the screen and waits Ior
you to type in the regular expression. Press the Return key to Iinish; vi then
searches Iorward Ior the next occurrence oI the regular expression. For
example, press /the Iollowed by Return. This moves Iorward to the next
occurrence oI the, perhaps imbedded in the middle oI some longer word (other,
weather, etc.). II you just press / and then Return, vi searches Ior the next
occurrence oI whatever the last regular expression was that you searched Ior.
O n : Has the same eIIect as pressing / and then Return; i.e., searches Ior the next
occurrence oI whatever the last regular expression was that you searched Ior.
O ?reg_exp : Searches backward, rather than Iorward. II no regexp is given, it
searches Ior the last regular expression that was entered. Both / and ? wrap
around, so searching "below" the bottom or "above" the top oI the Iile is legal.
O N : Same as pressing ? and then Return.
2 Repeat Counts
Many oI the movement commands discussed above can be preceded with a repeat
count; the movement is simply repeated the given number oI times:
O 3w : Move Iorward three words
O 5k : Move up Iour characters
O 3fa : Find the third succeeding a in current line
O 6+ : Move down six lines
For some commands, the "repeat counts" has special meaning:
O 4H : Move to Line 4 on the screen (home plus 3)
O 8L : Move to the eigth line Irom the bottom oI the screen
O 3$ : Move to the end oI the third line down
For some commands (e.g., `) the repeat count is ignored; Ior others (e.g., / and ? ) it is
illegal
3 Deleting Text
We've seen that dd deletes the current line. This can be used with a repeat count: 3dd
deletes three lines, the current line, and the two Iollowing lines.
The d command can be used as a "preIix" on most oI the movement commands above
to delete nearly arbitrary chunks oI text. When used with d, the movement commands
are called target speciIiers. d can be given a repeat count. (As you try these
experiments, remember to press u aIter each command to undo the deletion).
O dw : Delete "small" word Iorward
O d3w : Delete three "small" words Iorward
O 3dw : Three times, delete "small" word Iorward
O 3d3w : Three times, delete three "small" words Iorward (that is, delete nine
"small" words Iorward)
O d+ : Delete current line and next line down
O d/the : Delete Irom current character up to but not including the next
occurrence oI the pattern the.
O d$ : Delete to end oI line
O d : Delete to beginning oI line
O d3G : Delete Irom the curent line to and including Line 30
O dG : Delete Irom current line to and including last line
O dG : Delete Irom current line to and including Line 1
To delete single characters, use x. x can be given a repeat count:
O 5x : Delete current and 14 Iollowing characters
x is actually just an abbreviation oI d1; that is, delete one character right.
4 Changing Text
The c command is similar to d, except it toggles vi into Insert Mode, allowing the
original (unwanted) text to be changed to something else.
For example, put the cursor on the beginning oI a word (press w to get to the
beginning oI the next word). Then, press cw to change that word. On the screen, the
last character in the word being changed will be replaced with a $ symbol indicating
the boundary oI the change; type in a new word (you will overwrite the original word
on the screen) and press the ESC key when done. our input may be longer or shorter
than the word being changed.
Put the cursor at the beginning oI a line containing at least three words, and try c3w to
change three words. Try c$ to change to the end oI the current line. In all cases where
the change aIIects only the current line, the boundary oI the change is indicated with
$.
When a change aIIects more than just the current line, vi deletes the original text Irom
the screen and toggles into Insert Mode. For example, try c3 to change the current
and the next three lines; vi deletes the Iour original lines Irom the screen and toggles
into Insert Mode in a new blank line. As usual, press the ESC key when you have
Iinished entering your new text.
Some other change commands:
O cc : Change current line
O 5cc : Change Iive lines (current and next Iour)
O c/the : Change Irom current character up to but not including the next
occurrence oI the pattern the
O c$ : Change to end oI line
O c3G : Change Irom the current line to and including Line 30
O cG : Change Irom curernt line to and including last line
O cG : Change Irom curernt line to and including Line 1
5 Yanking (Copying) Text
The y command yanks a copy oI text into a buIIer; the yanked text can then be put (or
pasted) elsewhere in the Iile using p or P.
The simplest Iorm oI yank is yy to yank the current line; aIter yy, try p to put a copy
oI the yanked line aIter the cursor. Following yy, you can make as many copies oI the
yanked line as you want by moving up and down in the Iile and pressing p.
To copy multiple lines, try, Ior example, 5yy (yank the current and next Iour lines). p
puts a copy oI the yanked lines aIter the cursor; the sequence 5yyp "works" but it
probably doesn't do what you would like. The P command is like p, but puts a copy oI
the yanked text ahead oI the cursor; try the sequence 5yyP.
Other yank commands:
O y3w : ank three words
O y$ : ank to end oI current line
O yG : ank Irom current line to and including Line 1
6 Filtering text
The Iilter command !, prompts Ior the name oI a UNIX command (which should be a
Iilter), then passes selected lines through the Iilter, replacing those selected line in
the vi buIIer with the output oI the Iilter command. vi's ability to pass nearly arbitrary
chunks oI text through any UNIX Iilter adds incredible Ilexibility to vi, at no
"additional cost" in size or perIormance to vi itselI.
Some examples will help illustrate. Create a line in your Iile containing just the word
who and absolutely no other text. Put the cursor on this line, and press !!This
command is analogous to dd, cc, or yy, but instead oI deleting, changing, or yanking
the current line, it Iilters the current line. When you press the second !, the cursor
drops down to the lower leIt corner oI the screen and a single ! is displayed,
prompting you to enter the name oI a Iilter. As the Iilter name, type sh and press the
Return key. sh (the Bourne shell) is a Iilter! It reads standard input, does some
processing oI its input (that is, executes commands), and sends its output (the output
oI those commands) to standard output. Filtering the line containing who through sh
causes the line containing who to be replaced with a list oI the current users on the
system - right in your Iile!
Try repeating this process with date. That is, create a line containing nothing but the
word date, then put the cursor on the line, and press !!sh and the Return key. The line
containing date is replaced with the output oI the date command.
Put your cursor on the Iirst line oI the output oI who. Count the number oI lines.
Suppose, Ior example, the number is six. Then select those six lines to be Iiltered
through sort; press 6!!sort and the Return key. The six lines will be passed through
sort, and sort's output replaces the original six lines.
The Iilter command can only be used on complete lines, not on characters or words.
Some other Iilter commands (here, CR ~ means press Return):
O !/the < CR > sort < CR > : Sort Irom the current line up to and including the
next line containing the
O !Ggrep the < CR > : Replace Irom the current line to and including Line 1
with just the lines that contain the
O !Gawk 'print $]' < CR > : From the current line to the end oI Iile, replace
every line with just its Iirst word.
7 Marking Lines and Characters
ou can mark lines and characters to be used as targest Ior movement, deletion,
change, yanking, and Iiltering using the command mc, where c is a lowercase letter.
For example, put the cursor in the middle oI some word and press ma. This marks the
character under the cursor as mark a.
Now, move the cursor oII the marked character and to a diIIerent line ( use the cursor
keys, CTRL-u, or whatever). To return to the marked line, press 'a (that is, single
quote, then a). This moves to the Iirst non-white space character on the line containing
mark a.
Move oII that line again. To return to the marked character, press `a (that is,
backquote, then a). This moves on top oI the character marked with a.
Marking is usually used with deleting, changing, yanking or Iiltering. For example,
move the cursor to a line other than the one containing mark a, and then press d'a (d,
single quote, a). This deletes Irom the current line to and including the line marked
with a.
Put the cursor in the middle oI a diIIerent word and press mb to set mark b. Now,
move the cursor away Irom that word (but only a Iew lines, so you can see what we're
about to do more easily), and then press d`b (d, backquote, b). This deletes Irom the
current CHARACTER to and including the CHARACTER marked with b.
As another example, to sort the output oI who, mark the Iirst line (ma), then move the
cursor to the last line and press !'asort and the Return key.
II you jump to a mark and decide you want to jump back to whatever you jumped
Irom, you can press '' (jump back to line) or `` (jump back to character).
8 Naming Buffers
When you delete, change, or yank text, the original text is stored (until the next delete,
change, or yank) in an unnamed buIIer Irom which it can be put using p or P. Using
the unnamed buIIer, only the most recently deleted, changed or yanked text may be
recovered.
II you wish to delete, change, or yank multiple sections oI text and remember them all
(up to a maximum oI 26), you can give a buIIer name ahead oI the delete change or
yank command. A buIIer name has the Iorm "c (double quote, lowercase c).
For example, press "ayy to yank the current line into buIIer a, then move to a diIIerent
line and press "byy to yank that line into buIIer b. Now, move elsewhere in the Iile
and press "ap and "bp to put copies oI the text stored in buIIers a and b.
Some other named buIIer commands:
O "a6yy : ank six lines (current and next Iive) into buIIer a
O "bdG : Delete Irom the curernt line to and including Line 1, storing the
deleted lines in buIIer b
O "cy'c : ank Irom the current line to the line marked c into buIIer c (marks and
buIIers are distinct, and may have the same name without conIusing vi)
9 Substitutions
To substitute one chunk oI text Ior another in lines throughout your Iile, use the :s
command. Some substitute examples:
O :,$s/the/THE/g From Line 1 to the last line (line $), substitute Ior the text
THE; do this globally in each line where the occurrs
O :'a,s/`/ha ha/ From the line marked a to the current line (line .), substitute Ior
everything on the line the text ha ha
Miscellaneous "Colon Commands"
All colon commands begin with a colon; when you press the colon, the cursor drops to
the lower leIt corner oI the screen, and a colon prompt is displayed waiting Ior you to
Iinish your colon command.
Some important examples:
O :w Write the buIIer contents to the Iile without quitting Irom vi
O :w abc Write the buIIer contents to the Iile abc (creating abc iI it doesn't exist,
or overwriting current contents iI it does exist) without quitting Irom vi
O :,w abc Write lines 1 through 10 to Iile abc
O :'a,$w abc Write Irom the line marked a to the last line into Iile abc
O :e abc Edit Iile abc, instead oI the current Iile. vi prints an error message iI
changes have been made to the curernt Iile that have not been saved with :w
O :e! abc Edit Iile abc, throwing away any changes that may have been made to
the current Iile
O :e # Edit the prior Iile edited (successive :e# commands toggle back and Iorth
between two Iiles)
O :f abc Change the Iile anme Ior the current vi buIIer to abc
O :q Quit, unless unsaved chanegs have been made
O :q! Quit, throwing away any changes that may have been made
O :r abc Read the Iile abc into current vi buIIer, aIter the line the cursor is on (try
:r croc to read in a copy oI the croc Iile)
O :!cmd Execute command cmd (who, sort, ls, etc.)
Setting Options
Various options aIIect the "Ieel" oI vi. ou can display all the various options that can
be set using the colon command :set all. ou can also use set to change options.
For example, iI you want to see line numbers Ior the lines in the Iile you're editing,
use the command :set number. To turn oII line numbering, use the command :set
nonumber. Most options can be abbreviated; :set nu turns on line numbering and :set
nonu turns oII line numbering.
II you :set nomagic, the special meanings oI regular expression characters (period,
asterisk, square bracket, etc.) are switched oII. Use :set magic to restore the special
meanings.
Some options take a value. For example, :set tabstop4 causes tabs to be displayed as
Iour space characters, rather than the usual eight.
II you Iind you always want certain options set certain ways, you can put the set
commands you want ina Iile .exrc, or you can set up the environment variable
EXINIT to speciIy the options you want.
For example, iI your login shell is Bourne shell, this line could go in your .proIile Iile:

EXINIT='set nomagic nu tabstop=4'; export EXINIT

II your login shell is a C shell, this line could go in your .login Iile:

setenv EXINIT 'set nomagic nu tabstop=4'

2 Key Mappings
II you Iind you're perIorming a series oI simple commands over and over, you can
map the command series to an unused command key using the :map command. II
your mapping must include control characters such as Return key (CTRL-M in
ASCII) or the ESC (CTRL-| in ASCII) key, precede such characters with CTRL-v to
suppress their usual special meaning.
For example, this command maps CTRL-A to move the cursor Iorward 55 lines, then
back up to the most recent blank line, then change that blank line to a IormIeed
(CTRL-L) and three blank lines. That is, each CTRL-A will paginate the next page,
without splitting paragraphs across pages.
Note: In this command, each control character is shown as `C, where C is some
uppercase letter. For example, CTRL-M is shown as `M. Also, when you enter this
command you will not see the CTRL-v characters as shown: each CTRL-v merely
suppresses the usual special meaning oI the Iollowing control character, so when you
press the sequence `V`M, all you will see on the screen is `M. In this command, `M
is the Return key and `| is the ESC key.

:map ^A 55+.^$^V^Mcc^V^L^V^M^V^M^V^M^V^

3 Editing Multiple Files
ou can edit multiple Iiles with vi by giving multiple Iile names as command line
arguments:

vi croc fatherw wknight

Three colon commands are used to move through the multiple Iiles:
O :n Move to the next Iile in the argument list (you must save changes with :w
or vi will print an error message)
O :N Move to the previous Iile in the argument list (you must save changes with
:w or vi will print an error message)
O :rew Rewind and start over with the Iirst Iile in the argument list
The :n, :N, and :rew commands are somewhat clumsy, but there are some important
beneIits: the contents oI named buIIers ("a, "b, "c, etc.) are remembered across Iiles,
so you can use :n and :rew with p and P to copy text back and Iorth between Iiles.
Also, the most recent search string Ior the / and ? commands remembered across Iiles,
so you can do repetitive searches in multiple Iiles rather easily.
For example, try the Iollowing experiment: First get out oI vi, then execute vi with
croc and wknight as arguments:

$ vi croc wknight

In croc, search Ior the
/the < CR >
ank this line into buIIer a:
"ayy
Now go to the next Iile (you've made no change to croc, so this will work):
:n < CR >
Search Ior the "next" line containing the, without retyping the search string:
n
Put a copy oI buIIer a aIter the current line in wknight:
"ap
Move down two lines, and yank the current line into buIIer b:
jj"byy
Save the changes to wknight
:w < CR >
Now, rewind to croc
:rew < CR >
Search again, and put a copy oI buIIer b aIter the Iound line:
n"bp
Save the changes, and exit vi
ZZ
4 Final Remarks
This tutorial was intended to introduce some oI the vi capabilities that you might
overlook in your system's vi manual or that might not be mentioned in the manual
(diIIerent systems have manuals oI widely varying quality).
ou will not be a vi expert aIter reading this tutorial, but you will have a good
appreciation oI vi's capabilities. Only time and eIIort can make a vi expert. But the
eIIiciency and universality oI vi make this eIIort pay oII in the long run.
ou may have decided you hate vi. So be it! But be aware that vi remains the standard
UNIX text editor - the one editor you can count on being available on every UNIX
system you'll use - so even iI you preIer to use something else day-to-day, you'd be
well advised to know the bare minimum vi material covered in this tutorial.

Vim Reference Card
Vi states
Vi has 3 modes:
1. .ommand mode - Normal and initial state; others return here (use ESC to abort
a partially typed command)
2. input mode - entered by speciIic commands a i A I o O c C s S R and ended
by ESC or abnormally with interrupt
3. ine mode - i.e. waiting Ior input aIter a : , / , ? or a ! command (end with CR,
abort with CTRL-c). CTRL is the control key: CTRL-c means "control c"
2 Shell Commands
1. TERM code Puts a code name Ior your terminal into the variable TERM
2. export TERM Conveys the value oI TERM (the terminal code) to any UNIX
system program that is terminal dependant.
3. tput init Initializes the terminal so that it will Iunction properly with various
UNIX system programs.
4. vi filename Accesses the vi screen editor so that you can edit a speciIied Iile.
5. vi file1 file2 file3 Enters three Iiles into the vi buIIer to be edited. Those Iiles
are file1, file2, and file3.
6. view file Invoke vi editor on file in read-only mode
7. vi -R file Invoke vi editor on file in read-only mode
8. vi -r file Recover file and recent edits aIter system crash
9. vi -r file Recover file and recent edits aIter system crash
3 Setting Options
1. :set option Activate option
2. :set optionvalue Assign value to option
3. :set no option Deactivate option
4. :set Display options set by user
5. :set all Display list oI all current options, both deIault and those set by the user
6. :set option? Display values oI option
4 Notations used
Notations:
1. CTRL-c CTRL is the control key: CTRL-c means "control c"
2. CR is Carriage return (ENTER key)
5 Interrupting, cancelling
O ESC end insert or incomplete command
O CTRL-? CTRL is the control key: CTRL-? means "control ?" delete or rubout
interrupts
O CTRL-l reprint/reIresh screen iI CTRL-? scrambles it
6 File Manipulation
O ZZ Save the Iile and exit vi
O :wq Save the Iile and exit vi
O :w Write the current Iile
O :w! Force write the current Iile, iI Iile is read-only
O :wname Write to Iile name
O :q Exit Irom vi
O :q! Force exit Irom vi (discarding changes)
O :e name Edit Iile name
O :e! reedit, discard changes
O :e + name edit Iile name, starting at end
O :e + n edit starting at line n
O :e # edit alternate Iile
O :n edit next Iile in arglist
O :args list Iiles in current Iilelist
O :rew rewind current Iilelist and edit Iirst Iile
O :n args speciIy new arglist
O :f show current Iile and line
O CTRL-G synonym Ior :I , show current Iile and line
O :ta tag to tag Iile entry tag
O CTRL-] :ta, Iollowing word is tag
7 Movement
O Arrows Move the cursor
O CTRL-d Scroll halI page down
O CTRL-u Scroll halI page up
O CTRL-f Scroll a Iull page down
O CTRL-b Scroll a Iull page up
O : Move to start oI Iile
O :n Move to line number n
O :$ Move to end oI Iile
O Move to start oI line
O ^ Move to Iirst non-blank character
O $ Move to end oI line
O CR Move to the start oI next line
O - Move to the start oI previous line
O Find matching bracket
O G goto line (last line deIault)
O ]] next section/Iunction
O previous section/Iunction
8 Line Positioning
O H Home window line
O L Last window line
O M Middle window line
O + Next line, at Iirst non-white
O - Previous line, at Iirst non-white
O CR return, same as
O j next line, same column
O k previous line, same column
9 Character positioning
O beginning oI line
O $ end oI line
O h Iorward
O l backwards
O SPACE same as l
O fx Iind x Iorward
O Fx Iind x backward
O ; repeat last I F
O , inverse oI ;
O [ to speciIied column
O Iind matching or }
Words, sentences, paragraphs
O w Word Iorward
O b Word backward
O e End oI word
O ) To next sentence
O ( Back sentence
O ] To next paragraph
O Back paragraph
O W Blank delimited word
O B Back W
O E To end oI W
Marking and returning
O `` (press twice the back-quote ` key) Previous context
O '' (press twice the single-quote ` key) Previous context at Iirst non-white in line
O mx mark position with letter x
O `x (back quote key and letter x) goto mark x
O 'x goto mark x at Iirst non-white in line
2 Corrections during insert
O CTRL-h Erase last character
O CTRL-w Erase last word
O erase Press DELETE key, same as CTRL-h
O kill our kill key, erase input this line
O \ Escapes CTRL-h, DELETE and kill
O ESC Ends insertion, back to command
O CTRL-? Interrupt, terminates insert
O CTRL-d Backtab over autoindent
O CTRL-v Quote non-printing character
3 Adjusting the screen
O CTRL-l Clear and redraw
O CTRL-r retype, eliminate lines
O z-CR redraw, current line at window top
O z- redraw, current line at window bottom
O z redraw, current line at window center
O /pat/z- pat line bottom
O tn Use n line window
O CTRL-e Scroll window down 1 line
O CTRL-y Scroll window up 1 line
4 Delete
O x Delete the character under the cursor
O X Delete the charater beIore the cursor
O D Delete to the end oI line
O d^ Delete back to start oI line
O dd Delete the current line
O ndd Delete n lines starting with the current one
O dnw Delete n words starting Irom cursor
5 Insert, change
O i Enter input mode inserting beIore the cursor
O I Enter input mode inserting beIore the Iirst non-blank character
O a Enter input mode inserting aIter the cursor
O A Enter input mode inserting aIter the end oI the line
O o Open a new line below current line and enter input mode
O O Open a new line above current line and enter input mode
O r Replace the character under the cursor (does NOT enter input mode)
O R Enter input mode replacing characters
O C shiIt-c. Change rest oI line
O D shiIt-d. Delete rest oI line
O s Substitute chars
O S Substitute lines
O 1 Join lines
O 1 Join lines
6 Copy and Paste
The "yank buIIer" is Iilled by EJERY delete command, or explicitely by Y and yy.
O Y Copy the current line to the yank buIIer
O nyy Copy n lines starting Irom the current to the yank buIIer
O p Paste the yank buIIer aIter the cursor (or below the current line)
O P Paste the yank buIIer beIore the cursor (or above the current line)
O "p Put Irom buIIer x
O "y ank to buIIer x
O "d Delete into buIIer x
7 Operators (use double to affect lines)
O d delete
O c change
O < leIt shiIt
O > right shiIt
O ! Iilter through command
O indent Ior LISP
O y yank text to buIIer
8 Search and replace
O /tet Search Iorward Ior text
O ?tet Search backward Ior text
O n Repeat the last search in the same direction
O N Repeat the last search in the reverse direction
O / Repeat the last search Iorward
O ? Repeat the last search backward
O addr ] s/from/to/ g ] Search Ior the occurence oI from and replace it
with to in the current line, or in the range addr (two line numbers seperated by
command; 1,$ is the whole Iile). Replaces one occurrence per line, or all
occurrences iI g is speciIied. For example, :3,20s/someword/anotherword/g
Will replace "someword" with "anotherword" starting Irom line 3 to line 20. 'g'
is global means replace all occurrences oI "someword".
9 General
O :sh Forks a shell (to be exited with CTRL-d)
O :!.ommand Forks a shell to execute command
O :set number Switch on line numbering
O :set nonumber Switch oII line numbering
2 Line Editor Commands
O : Tells vi that the next commands you issue will be line editor commands.
O :sh Temporarily returns to the shell to perIorm some shell commands without
leaving vi.
O CTRL-d Escapes the temporary return to the shell and returns to vi so you can
edit the current window.
O :n Goes to the nth line oI the buIIer.
O :x,:w filename Writes lines Irom the numbers x through the number : into a
new Iile called filename.
O :$ Moves the cursor to the beginning oI the last line in the buIIer.
O :,$d Deletes all the lines Irom the current line to the last line
O :r filename Inserts the contents oI the Iile filename under the current line oI the
buIIer.
O :s/text/newtext/ Replaces the Iirst instance oI text on the current line
with newtext
O :s/text/newtext/g Replaces the every occurrence oI text on the current line
with newtext
O :g/text/s//newtext/g Changes every occurrence oI text on the buIIer
to newtext.
2 Other commands
O u Undo the last change
O U Restore the current line
O ~ Change case
O 1 Join the currentline with the next line
O Repeat last text changing command
O CTRL-g Show Iile name and line number

2 Related URLs
Related VIM URLs are at -
O C and C++ 8eauLlfer hLLp//wwwmeLalabuncedu/Lu/PCW1C/C
C++8eauLlflerPCW1ChLml
O Llnux goodles maln slLe ls aL hLLp//wwwaldev8mcom Mlrror slLes are aL
hLLp//aldev0web[umpcom angelflre geoclLles vlrLualave 30megs Lheglob
en8Cl 1errashare lorLuneclLy lreewebslLes 1rlpod Spree Lscallx PLLpclLy
lreeservers
3 Other Formats of this Document
This document is published in 14 diIIerent Iormats namely - DVI, Postscript, Latex,
Adobe Acrobat PDF, LyX, GNU-inIo, HTML, RTF(Rich Text Format), Plain-text,
Unix man pages, single HTML Iile, SGML (Linuxdoc Iormat), SGML (Docbook
Iormat), MS WinHelp Iormat.
This howto document is located at -
O hLLp//wwwllnuxdocorg and cllck on PCW1Cs and search for howLo
documenL name uslng C18L+f or AL1+f wlLhln Lhe webbrowser
ou can also Iind this document at the Iollowing mirrors sites -
O hLLp//wwwcalderacom/Lu/PCW1C
O hLLp//wwwllnuxuclaedu/Lu
O hLLp//wwwccgaLechedu/llnux/Lu
O hLLp//wwwredhaLcom/mlrrors/Lu
O CLher mlrror slLes near you (neLworkaddresswlse) can be found
aL hLLp//wwwllnuxdocorg/mlrrorshLml selecL a slLe and go Lo dlrecLory
/Lu/PCW1C/xxxxxPCW1ChLml
O ?ou can geL Lhls PCW1C documenL as a slngle flle Lar ball ln P1ML uvl
osLscrlpL or SCML formaLs from
fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C/oLher
formaLs/ and hLLp//wwwllnuxdocorg/docshLml#howLo
O laln LexL formaL ls
ln fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C and hLLp//wwwllnuxdoc
org/docshLml#howLo
O Slngle P1ML flle formaL ls ln hLLp//wwwllnuxdocorg/docshLml#howLo
Single HTML Iile can be created with command (see man sgml2html) -
sgml2html -split 0 xxxxhowto.sgml
O 1ranslaLlons Lo oLher languages llke lrench Cerman Spanlsh Chlnese
!apanese are
ln fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C andhLLp//wwwllnuxdoc
org/docshLml#howLo Any help from you Lo LranslaLe Lo oLher languages ls
welcome
1he documenL ls wrlLLen uslng a Lool called SCML1ools whlch can be goL from
hLLp//wwwsgmlLoolsorg Complllng Lhe source you wlll geL Lhe followlng
commands llke
O sgml2hLml xxxxhowLosgml (Lo generaLe hLml flle)
O sgml2hLml spllL 0 xxxxhowLosgml (Lo generaLe a slngle page hLml flle)
O sgml2rLf xxxxhowLosgml (Lo generaLe 81l flle)
O sgml2laLex xxxxhowLosgml (Lo generaLe laLex flle)
3 Acrobat PDF format
PDF Iile can be generated Irom postscript Iile using either
acrobat distill or Ghostscript. And postscript Iile is generated Irom DVI which in
turn is generated Irom LaTex Iile. ou can download distill soItware
Irom http://www.adobe.com. Given below is a sample session:

bash$ man sgml2latex
bash$ sgml2latex filename.sgml
bash$ man dvips
bash$ dvips -o filename.ps filename.dvi
bash$ distill filename.ps
bash$ man ghostscript
bash$ man ps2pdf
bash$ ps2pdf input.ps output.pdf
bash$ acroread output.pdf &

Cr you can use ChosLscrlpL command ps2pdf ps2pdf ls a workallke for nearly all Lhe
funcLlonallLy of Adobes AcrobaL ulsLlller producL lL converLs osLScrlpL flles Lo
orLable uocumenL lormaL (ul) flles ps2pdf ls lmplemenLed as a very small
command scrlpL (baLch flle) LhaL lnvokes ChosLscrlpL selecLlng a speclal ouLpuL
devlce called pdfwr|te ln order Lo use ps2pdf Lhe pdfwrlLe devlce musL be lncluded
ln Lhe makeflle when ChosLscrlpL was complled see Lhe documenLaLlon on bulldlng
ChosLscrlpL for deLalls
32 Convert Linuxdoc to Docbook format
This document is written in linuxdoc SGML Iormat. The Docbook SGML Iormat
supercedes the linuxdoc Iormat and has lot more Ieatures than linuxdoc. The linuxdoc
is very simple and is easy to use. To convert linuxdoc SGML Iile to Docbook SGML
use the program ld2dbsh and some perl scripts. The ld2db output is not 100 clean
and you need to use the clean_ld2dbpl perl script. ou may need to manually correct
Iew lines in the document.
O uownload ld2db program
from hLLp//wwwdcsglaacuk/rrL/docbookhLml or from Al uev slLe
O uownload Lhe cleanup_ld2dbpl perl scrlpL from from Al uev slLe
1he ld2dbsh ls noL 100 clean you wlll geL loLs of errors when you run

bash$ ld2db.sh file-linuxdoc.sgml db.sgml
bash$ cleanup.pl db.sgml db_clean.sgml
bash$ gvim db_clean.sgml
bash$ docbook2html db.sgml

And you may have Lo manually edlL some of Lhe mlnor errors afLer runnlng Lhe perl
scrlpL lor eg you may need Lo puL closlng Lag /ara for each LlsLlLem
33 Convert to MS WinHelp format
ou can convert the SGML howto document to MicrosoIt Windows Help Iile, Iirst
convert the sgml to html using:

bash$ sgml2html xxxxhowto.sgml (to generate html file)
bash$ sgml2html -split 0 xxxxhowto.sgml (to generate a single page
html file)

1hen use Lhe Lool PLml1oPlp ?ou can also use sgml2rLf and Lhen use Lhe 81l flles for
generaLlng wlnhelp flles
34 Reading various formats
In order to view the document in dvi Iormat, use the xdvi program. The xdvi program
is located in tetex-xdvi*.rpm package in Redhat Linux which can be located through
ControlPanel , Applications , Publishing , TeX menu buttons. To read dvi document
give the command -
xdvi -geometry 80x90 howto.dvi
man xdvi
And reslze Lhe wlndow wlLh mouse 1o navlgaLe use Arrow keys age up age
uown keys also you can use f d u c l r p n leLLer keys Lo move up down
cenLer nexL page prevlous page eLc 1o Lurn off experL menu press x
ou can read postscript Iile using the program 'gv' (ghostview) or 'ghostscript'. The
ghostscript program is in ghostscript*.rpm package and gv program is in gv*.rpm
package in Redhat Linux which can be located through ControlPanel , Applications ,
Graphics menu buttons. The gv program is much more user Iriendly than ghostscript.
Also ghostscript and gv are available on other platIorms like OS/2, Windows 95 and
NT, you view this document even on those platIorms.
O CeL ghosLscrlpL for Wlndows 93 CS/2 and for all CSes
from hLLp//wwwcswlscedu/ghosL
To read postscript document give the command -
gv howto.ps
ghostscript howto.ps
ou can read HTML Iormat document using Netscape Navigator, MicrosoIt Internet
explorer, Redhat Baron Web browser or any oI the 10 other web browsers.
ou can read the latex, LyX output using LyX a X-Windows Iront end to latex.
4 Copyright Notice
Copyright policy is GNU/GPL as per LDP (Linux Documentation project). LDP is a
GNU/GPL project. Additional restrictions are - you must retain the author's name,
email address and this copyright notice on all the copies. II you make any changes or
additions to this document then you should notiIy all the authors oI this document.
Vim Color Editor HOW-TO (Vi Improved
with syntax color highlighting)
Al Dev (Alavoor Vasudevan) alavooryahoocom
v172 28 !une 2001

1bls Jocomeot ls o qolJe to polckly settloq op tbe vlm colot eJltot oo lloox ot uolx
systems 1be lofotmotloo bete wlll lmptove tbe ptoJoctlvlty of ptoqtommets becoose
tbe vlm eJltot soppotts syotox colot blqbllqbtloq ooJ bolJ foots lmptovloq tbe
teoJoblllty of ptoqtom coJe A ptoqtommets ptoJoctlvlty lmptoves 2 to J tlmes
wltb o colot eJltot llke vlm 1be lofotmotloo lo tbls Jocomeot opplles to oll opetotloq
sytems wbete vlm wotks socb os lloox wloJows 95/N1 Apple Moc l8M O5es vM5
8eO5 ooJ oll flovots of uolx llke 5olotls nlu\ Al\ 5cO 5lolx 85u ulttlx etc (lt
meoos olmost oll opetotloq systems oo tbls plooet!)

Introduction
O 11 8efore you lnsLall
O 12 lnsLall vlm on 8edhaL Llnux
O 13 lnsLall vlm on Cnu ueblan Llnux
O 14 lnsLall vlm on unlxes
O 13 lnsLall vlm on MlcrosofL Wlndows 93/n1
O 16 lnsLall vlm on vMS
O 17 lnsLall vlm on CS/2
O 18 lnsLall vlm on Apple MaclnLosh
2 Install Vim on Microsoft Windows 95/NT
O 21 lnsLall bash shell
O 22 LdlL bash_proflle
O 23 SeLup Wlndow colors
3 Setup gvim init files
O 31 Sample gvlmrc flle
O 32 xdefaulLs parameLers
4 Color Syntax init files
O 41 AuLo sourceln meLhod
O 42 Manual meLhod
5 VIM Usage
6 Vi companions
O 61 CLags for LSCL
O 62 CLags for !avaScrlpL programs korn 8ourne shells
O 63 uebugger gdb
7 Online VIM help
8 Vim Home page and Vim links
9 Vim Tutorial
O 91 vlm Pandson 1uLorlal
O 92 vl 1uLorlals on lnLerneL
Vi Tutorial
O 101 Cursor MovemenL Commands
O 102 8epeaL CounLs
O 103 ueleLlng 1exL
O 104 Changlng 1exL
O 103 ?anklng (Copylng) 1exL
O 106 lllLerlng LexL
O 107 Marklng Llnes and CharacLers
O 108 namlng 8uffers
O 109 SubsLlLuLlons
O 1010 Mlscellaneous Colon Commands
O 1011 SeLLlng CpLlons
O 1012 key Mapplngs
O 1013 LdlLlng MulLlple llles
O 1014 llnal 8emarks
Vim Reference Card
O 111 vl sLaLes
O 112 Shell Commands
O 113 SeLLlng CpLlons
O 114 noLaLlons used
O 113 lnLerrupLlng cancelllng
O 116 llle ManlpulaLlon
O 117 MovemenL
O 118 Llne oslLlonlng
O 119 CharacLer poslLlonlng
O 1110 Words senLences paragraphs
O 1111 Marklng and reLurnlng
O 1112 CorrecLlons durlng lnserL
O 1113 Ad[usLlng Lhe screen
O 1114 ueleLe
O 1113 lnserL change
O 1116 Copy and asLe
O 1117 CperaLors (use double Lo affecL llnes)
O 1118 Search and replace
O 1119 Ceneral
O 1120 Llne LdlLor Commands
O 1121 CLher commands
2 Related URLs
3 Other Formats of this Document
O 131 AcrobaL ul formaL
O 132 ConverL Llnuxdoc Lo uocbook formaL
O 133 ConverL Lo MS WlnPelp formaL
O 134 8eadlng varlous formaLs
4 Copyright Notice
C++ Programming HOW-TO
Al Dev (Alavoor Vasudevan) alavooryahoocom
v403 26 !uly 2001

1bls Jocomeot ptovlJes o comptebeoslve llst of c-- ukl polotets lloks to c-- oolloe
textbooks ooJ ptoqtommloq tlps oo c-- 1bls Jocomeot olso ptovlJes o c-- llbtoty
wblcb lmltotes Iovolooqooqe ooJ wblcb bos votloos metboJs to ovolJ memoty
ptoblems lo c-- usloq tbls llbtoty yoo coo complle Iovos sootce coJe ooJet c-- 1bls
Jocomeot setves os o nome of c-- looqooqe 1be lofotmotloo qlveo bete wlll belp
yoo to ptoqtom ptopetly lo c-- looqooqe ooJ opplles to oll tbe opetotloq systems
tbot ls lloox M5 uO5 8eO5 Apple Moclotosb O5 Mlctosoft wloJows
95/98/N1/2000 O5/2 l8M O5es (Mv5 A5/400 etc) vA\ vM5 Novell Netwote oll
flovots of uolx llke 5olotls nlu\ Al\ 5cO 5lolx 85u etc ooJ to oll otbet opetotloq
systems wblcb soppott c-- compllet (lt meoos olmost oll tbe opetotloq systems oo
tbls plooet)

Introduction
O 11 C++ v/s !ava
O 12 Whlch one Ada93 C C++ or !ava ??
O 13 roblems faclng Lhe currenL C++ compllers
O 14 CCC C++ Cb[ecL CrlenLed rogrammlnglanguage
2 String Class Varieties
O 21 MulLlple lnherlLance Sample CusLom SLrlng class
3 Best C++ compilers for MS Windows
2/NT/95/98/ME/XP
4 Download String
5 How Can I trust Al Dev's String Class ??
6 Usage of String class
O 61 CperaLors
O 62 luncLlons
7 Stringh file
O 71 SLrlng8ufferh
O 72 SLrlng1okenlzerh
8 Renaming the String class
O 81 Case 1 Slmple rename
O 82 Case 2 8esolve confllcL
9 File Class
C++ Zap (Delete) function
Pointers are problems
2 Usage of my_malloc and my_free
O 121 Carbage CollecLor for C++
3 Debug files
4 1ava like API
5 IDE tools for C++
6 C++ Online Textbooks and Docs
7 C++ Coding Standards
8 C++ Online Docs
O 181 C++ 1uLorlals
O 182 useful llnks
O 183 C++ Culck8eference
O 184 C++ useneL newsgroups
9 Memory Tools
2 Related URLs
2 C++ Scripting Languages
O 211 lkL (C/C++ ScrlpLlng Language)
O 212 SofLlnLegraLlon Ch (C/C++ ScrlpLlng Language)
O 213 P (C++ ScrlpLlng Language)
22 Templates
23 STL References
O 231 Cvervlew of Lhe S1L
O 232 Peader llles
O 233 1he ConLalner Classes lnLerface
O 234 vecLors
O 233 lLeraLors and Lhe S1L
O 236 LlsLs
O 237 SeLs
O 238 Maps
O 239 S1L AlgorlLhms
24 Threads in C++
O 241 1hreads 1uLorlal
O 242 ueslgnlng a 1hread Class ln C++
25 C++ Utilities
26 Other Formats of this Document
O 261 AcrobaL ul formaL
O 262 ConverL Llnuxdoc Lo uocbook formaL
O 263 ConverL Lo MS WlnPelp formaL
O 264 8eadlng varlous formaLs
27 Translations To Other Languages
28 Copyright
29 Appendix A String Program Files
Introduction
The purpose oI this document is to provide you with a comprehensive list oI URL
pointers and programming tips on C. Also, this document provides a C library
having Java-like String class, string tokenizer, memory Iunctions and many other
Iunctions, which can be used in general C applications. Also various examples are
given here which demonstrate the usage oI this library.
This document is not a textbook on C, and there are already several excellent "on-
line Text books" on internet. II you are new to C and you never programmed in
C, then it is strongly suggested that you Iirst read the online C Textbooks given
in the chapter C Online Textbooks and then Iollow the subsequent chapters. It is
suggested that you purchase a textbook on C Ior reIerence Irom online bookstores
like amazon or barnes.
C++ v/s 1ava
C is one oI the most powerIul language and will be used Ior a long time in the
Iuture inspite oI emergence oI Java. C runs extremely fast and is in Iact to 2
times FASTER than Java. Java runs very slow because it is a byte-code-interpreted
language running on top oI "virtual machine". Java runs Iaster with JIT (Just-In-Time)
compiler, but it is still slower than C. And optimized C program is about 3 to 4
times faster than Java (with JIT compiler). Then, why do people use Java? Because it
is pure object oriented and is easier to program in Java, as Java automates memory
management, and programmers do not directly deal with memory allocations. This
document attempts to automate the memory management in C to make it much
more easy to use. The library given here will make C look like Java and will enable
"C" to compete with Java language.
Because oI manual memory allocations, debugging the C programs consumes a
major portion oI time. This document will give you some better ideas and tips to
reduce the debugging time.
2 Which one Ada95, "C", "C++" or 1ava ??
Language choice is very diIIicult. There are too many parameters - people, people
skills, cost, tools, politics (even national politics) and inIluence oI
businessmen/commercial companies. The best language based on technical merits
does not get selected simply due to political decisions!
Java is much closer to Ada95 than C. Java is derived Irom Ada95. Ada95 gets the
maximum points as per David Wheeler's Ada comparison chart. Ada got 93, Java
72, C 68 and C got 53. C and Java are closer in points(only 4
diIIerence), hence Java is not a very big revolution as compared to C. On other
hand, Ada is a very big revolution and improvement over C. The scores are like 4
students taking exams and student with highest score is Ada (93). Who knows?
Perhaps in Iuture Ada95 will replace Java!! Development costs oI Ada is halI oI C
as per Stephen F. Zeigler. Ada95 is available at -
O Ada home hLLp//wwwgnuadaorg
O Coogle Ada lndex
Since C programmers are abundant, it is recommended you do programming in
object-oriented "C" Ior all your application programming or general purpose
programming. ou can take Iull advantage oI object oriented Iacilities oI C. The
C compiler is lot more complex than "C" compiler and C programs may run bit
slower than "C" programs. But speed diIIerence between "C" and "C" is very
minute - it could be Iew milli-seconds which may have little impact Ior real-time
programming. Since computer hardware is becoming cheaper and Iaster and memory
'RAM' is getting Iaster and cheaper, it is worth doing code in C rather than "C" as
time saved in clarity and re-usability oI C code oIIsets the slow speed. Compiler
optimizer options like -O or -O3 can speed up C/C which is not available in Java.
Nowadays, "C" language is primarily used Ior "systems programming" to develop
operating systems, device drivers etc..
Note: &8ing the String, StringBuffer, String1okenizer and StringReader .a88e8
given in thi8 howto, you .an .ode in C++ whi.h "ea.ty" ook8 ike 1ava. 1hi8
do.ument trie8 to .o8e the gap between C++ and 1ava, by imitating 1ava .a88e8 in
C++
Java is platIorm independent language more suitable Ior developing GUI running
inside web-browsers (Java applets) but runs very slow. PreIer to use web-server-side
programming "Fast-CGI" with C and HTML, DHTML, XML to get better
perIormance. Hence, the golden rule is eb-server side programming use C and
web-client side (browser) programming use Java applets. The reason is - the server-
side OS (Linux) is under your control and never changes, but you will never know
what the client side web-browser OS is. It can be Internet appliance device (embedded
linuxnetscape) or computers running Windows 95/98/NT/2000 or Linux, Apple
Mac, OS/2, Netware, Solaris etc..
The advantage oI Java language is that you can create "Applets (GUI)" which can run
on any client OS platIorm. Java was created to replace the MicrosoIt Windows 95/NT
GUI APIs like MS Visual Basic or MS Visual C. In other words - "Java is the
cross-platIorm Windows-GUI API language oI next century". Many web-browsers
like Netscape supports Java applets and web-browser like Hot Java is written in java
itselI. But the price you pay Ior cross-platIorm portability is the perIormance,
applications written in Java run very slow.
Hence, Java runs on "client" and C runs on servers.
3 Problems facing the current C++ compilers
Since C is super-set oI C, it got all the bad Ieatures oI "C" language. Manual
allocation and deallocation oI memory is tedious and error prone (seeGarbage
Collector Ior C).
In "C" programming - memory leaks, memory overIlows are very common due to
usage oI Ieatures like -

Datatype char and char,
String functions like strcpy, strcat, strncpy, strncat, etc..
Memory functions like malloc, realloc, strdup, etc..

The usage oI char ` and strcpy causes horrible memory problems due
to overflow, fence past errors, memory corruption, step-on-others-toe(hurting
other variable's memory locations) or memory leaks. The memory problems are
extremely hard to debug and are very time consuming to Iix and trouble-shoot.
Memory problems bring down the productivity oI programmers. This document helps
in increasing the productivity oI programmers via diIIerent methods addressed to
solve the memory deIects in "C". Memory related bugs are very tough to crack, and
even experienced programmers take several days or weeks to debug memory related
problems. Memory bugs may be hide inside the code Ior several months and can
cause unexpected program crashes. The memory bugs due to usage oI char
` and pointers in C/C is costing $2 billion every year in time lost due to debugging
and downtime oI programs. II you use char ` and pointers in C then it is a very
costly aIIair, especially iI your program size is greater than 10,000 lines oI code.
Hence, the Iollowing techniques are proposed to overcome the Iaults oI "C" language.
Give preIerence in the Iollowing order -
1 use references lnsLead of polnLers
2 !ava sLyle SLrlng class (glven ln Lhls howLo) or S1uLlb sLrlng class
3 CharacLer polnLers (char *) ln C++ ||m|t the usage of char * Lo cases where you
cannoL use Lhe SLrlng class
4 CharacLer polnLers (char *) ln C uslng exLern llnkage speclflcaLlon lf you do noL
wanL Lo use (char *) ln C++
To use "C char *", you would put all your "C" programs in a separate Iile and link to
"C" programs using the linkage-specification statement extern "C" -

extern "C" ,
#include <stdlib.h
,

extern "C" ,
comp();
some_c_function();
,

The extern "C" is a linkage speciIication and is a Ilag that everything within the
enclosing block (brace-surrounded) uses C linkage, not C linkage.
The 'String class' utilises the constructor and destructor Ieatures to automate memory
management and provides access to Iunctions like ltrim, substring, etc..
See also related 'string class' in the C compiler. The string class is part oI the
standard GNU C library and provides many string manipulation Iunctions. Because
the C 'string class' and 'String class' library provides many string manipulation
Iunctions, there is less need to use the character pointer approach to write your own
string Iunctions. Also, C programmers must be encouraged to use 'new', 'delete'
operators instead oI using 'malloc' or 'Iree'.
The 'String class' does everything that char ` or char ] does. It can completely
replace char datatype. Plus added beneIit is that programmers do not have to worry
about the memory problems and memory allocation at all.
4 COOP - C++ Object Oriented Programming-language
A problem with C is that it is a superset oI C, and, although programmers can use
the good (object oriented) Ieatures oI C and avoid the bad Ieatures oI C, there is
nothing to Iorce them to do so. So, many C programs are written with no object
oriented Ieatures and continue to use the bad Ieatures oI C that the use oI C should
have overcome.
ThereIore, I propose that we create a new version oI C that does not allow the use
oI the bad Ieatures oI C.
I propose that this new version oI C be called COOP (say koop), which is an
acronym Ior C++ Object Oriented Programming-language" . COOP should be
pronounced like chicken coop. (The logo oI COOP language is a big Iat Hen inside
coop!) I propose that the Iile extension Ior COOP Iiles be .coo, which will not conIlict
with .c Ior C programs or .cpp Ior C programs.
To begin with, write the COOP as a Iront end to C. That is COOP pre-processes the
code syntax and then uses the standard C compiler to compile the program. COOP
acts as a Iront end to C compiler. (To start with, COOP will be a very good
project/thesis topic Ior university students)
The Iollowing are some other proposed Ieatures oI COOP:
O CCC wlll borrow some besL ldeas from MlcrosofL C# MlcrosofL puL loL of
efforLs and you can slmply uLlllze Lhem Specs are aL csharpspecs and seeC#
overvlew
O ls a subseL of C++ language buL wlll force programmer Lo use obe[cL orlenLed
programmlng
O ure Cb[ecLorlenLed langauge buL reLalns synLax of C++
O 8emove all bad or confuslng feaLures of C++ ln CCC for eg mulLlple
lnherlLance operaLor overloadlng llmlL usage of polnLers eLc
O revenL wrlLlng C llke programmlng ln CCC someLhlng whlch C++ currenLly
allows ueleLe all C feaLures whlch are consldered bad or
redundanL/dupllcaLes llke prlnLf fprlnLf malloc sLrucL free eLc
O no downward compaLlblllLy Lo C language
O Code wrlLLen ln CCC wlll be easy Lo malnLaln and ls easlly
undersLandable/readable
O Code wrlLLen ln CCC wlll be reusable (Lhru componenLs modules
ob[ecLs) SupporLs reusable sofLware componenLs Lhereby faclllLaLlng 8apld
AppllcaLlon uevelopmenL
O CCC ls slmple robusL CC has bare mlnlnum synLax (avoldlng confuslng
redundanL exLra consLrucLs of C++ for eg remove sLrucL and use class)
Also borrow ideas Irom -
O !ava Sun MlcrosysLem puL loL of efforL and you can slmply uLlllze LhaL
O ConnecLlve C++ aL hLLp//wwwqulnLessenLcom/producLs/cc++
2 String Class Varieties
The string class is the most vital object in programming, and string manipulations are
most extensively used and they comprise oI 20 to 60 oI total code. There are 3
variety oI string classes. OIcourse, you can build your own string class by simply
inheriting Irom these string classes -
O SLrlng class glven ln Lhls documenL Appendlx A SLrlngh
O Cnu sLrlng class
o Cnu C++ Llbrary unlv of 1ech
Sydney hLLp//wwwsocsuLseduau/doc/gnulnfo/llbg++/llbg++_18hLml
and users gulde
o mlrror slLe CesellschafL hLLp//www
alxgslde/doc/gnu/llbg++_18hLml#SLC23 and users gulde
o mlrror slLe 1echno
8ussla hLLp//wwwLechnospbru/xbaLob/lAC/Cnu/llbg++_19hLml#S
LC27 and users gulde
o mlrror slLe unlv of
uLah hLLp//wwwmaLhuLahedu/docs/lnfo/llbg++_19hLml#SLC27 and
users gulde
O CL SLrlng class aL hLLp//docLrollLechcom/qsLrlnghLml mlrror
aL hLLp//wwwcsberkeleyedu/dmarLln/qL/qsLrlnghLml
O lf none of Lhese alLernaLlves are sulLable you can bulld your own sLrlng class
?ou can sLarL wlLh one or more of Lhe prebullL classes llsLed above (by uslng
slngle or mulLlple lnherlLance)
2 Multiple Inheritance - Sample Custom String class
As mentioned above, you can build your own custom string class Irom the pre-built
classes by single or multiple inheritance. In this section we will build a sample custom
string class by using multiple inheritance, inheriting Irom the GNU string class and
the string class presented in Appendix H.
Start by downloading the sample Iile 'stringmulti.h' Irom Appendix A . That Iile is
reproduced below:

//
// Sample program to demonstrate constructing your own string class
// by deriving from the String class and stdlib's "string" class
//

#ifndef __STRING_MULTI_H_
#define __STRING_MULTI_H_

#include <string
#include "String.h"

// Important Notes: In C++ the constructors, destructors and copy
// operator are NJT inherited by the derived classes!!
// Hence, if the operators like =, + etc.. are defined in
// base class and those operators use the base class's contructors
// then you MUST define equivalent constructors in the derived
// class. See the sample given below where constructors mystring(),
// mystring(char,) are defined.
//
// Also when you use operator as in atmpstr + mstr, what you are really
// calling is atmpstr.operator+(mstr). The atmpstr is declared a
mystring

class mystring:public String, string
,
public:
mystring():String() ,, // These are needed for operator=, +
mystring(char bb,):String(bb) ,, // These are needed for
operator=, +
mystring(char bb,, int start, int slength):String(bb, start,
slength) ,,
mystring(int bb):String(bb) ,, // needed by operator+
mystring(unsigned long bb):String(bb) ,, // needed by
operator+
mystring(long bb):String(bb) ,, // needed by operator+
mystring(float bb):String(bb) ,, // needed by operator+
mystring(double bb):String(bb) ,, // needed by operator+
mystring(const String & rhs):String(rhs) ,, // Copy
Constructor needed by operator+
mystring(StringBuffer sb):String(sb) ,, // Java
compatibility
mystring(int bb, bool dummy):String(bb, dummy) ,, // for
StringBuffer class

int mystraa; // customizations of mystring
private:
int mystrbb; // customizations of mystring
,;

#endif // __STRING_MULTI_H_
3 Best C++ compilers for MS Windows
2/NT/95/98/ME/XP
Since MS Windows is quite popular Ior C development, the string class library
given in this document works well and runs very well on all the versions oI MS
Windows i.e. MS Win XP/2000/NT/95/98/ME. The C compilers Ior MS Windows
are :
O Cnu 8loodShed aL hLLp//wwwbloodshedneL/devcpphLml raLed 1sL (Lhe
besL among all)
O 8orland C++
compller hLLp//wwwborlandcom/bcppbullder/freecompller raLed 2nd
O MlcrosofL vlsual C++ compller hLLp//msdnmlcrosofLcom/vlsualc raLed 3rd
O MSuCS C++ compller hLLp//wwwdelorlecom/d[gpp
1he SLrlng class ln Lhls documenL ls LesLed wlLh all Lhe above compllers lL works flne
wlLh MS vlsual C++ compller v60 8orland C++ v32 8orland C++ compller v331 and
8loodshed compller
4 Download String
All the programs, examples are given in Appendix oI this document. ou can
download as a single tar zip, the String class, libraries and example programs Irom
O Co here and cllck on C++rogrammlng howLoLargz
flle hLLp//wwwaldev8mcom
O Mlrror slLes are aL
hLLp//aldev0web[umpcom angelflre geoclLles vlrLualave 30megs Lheglob
e n8Cl 1errashare lorLuneclLy lreewebslLes 1rlpodSpree Lscallx PLLpclLy
lreeservers
5 How Can I trust Al Dev's String Class ??
ou may a have question oI mis-trust on the String class soItware. To build
conIidence, there is a scientiIic method to veriIy the Iunctionality oI Al Dev's String
class. In modern days, computer scientists use the CPU power instead oI human brain
power to veriIy and validate the soItware. Human brain is too slow and hence it is
better to use the computer's power to test and validate soItware.
The program exampleString.cpp (and also given in Appendix A ) has regression test
module which you can use to run the regression tests several millions oI times
automatically. AIter running the regression tests on the String class you can certiIy
that the String class program is a ROCK SOLID and a BULLET-PROOF program.
I tested the String class with repeat cycle 5 and it ran and completed the
program without crash. While it is running I did not notice any memory leak. On
linux, I used /usr/bin/gtop, unix top command, KDEStart-~System-~KDE System
Gaurd and KDEStart-~System-~Process management to monitor the cpu and memory
usage.
I recommend that you start the regression test with repeat cycle equal to 10 million or
greater. The greater the repeat cycle number the greater will be your conIidence!!
Start the test and go to lunch and come back to see the results!!
6 Usage of String class
To use String class, you should Iirst reIer to a sample program "exampleString.cpp"
given in Appendix A and the String class which is given in Appendix A.
The 'String class' is a complete replacement Ior char and char * datatype. ou can
use 'String class' just like char and get much more Iunctionalities. ou should link
with the library 'libString.a' which you can build Irom the makeIile given in Appendix
A and copy the library to /usr/lib or /lib directory where all the "C" libraries are
located. To use the 'libString.a' compile your programs like -

g++ example.cpp -lString

See lllusLraLlon sample code as glven below

String aa;

aa = "Creating an Universe is very easy, similar to creating a baby
human.";

// You can use aa.val() like a 'char ' variable in programs
for (unsigned long tmpii = 0; tmpii < aa.length(); tmpii++)
,
//fprintf(stdout, "aa.val()%ld,=%c ", tmpii,
aa.val()tmpii,);
fprintf(stdout, "aa%ld,=%c ", tmpii, aatmpii,);
,

// Using pointers on 'char ' val ...
for (char tmpcc = aa.val(); tmpcc != 0; tmpcc++)
,
fprintf(stdout, "aa.val()=%c ", tmpcc);
,

6 Operators
The 'String class' provides these operators :-
O Lqual Lo
O noL equal Lo "
O AsslgnmenL
O Add Lo lLself and AsslgnmenL +
O SLrlng concaLenaLlon or addlLlon +
lor example Lo use operaLors

String aa;
String bb("Bill Clinton");

aa = "put some value string"; // assignment operator
aa += "add some more"; // Add to itself and assign operator
aa = "My name is" + " Alavoor Vasudevan "; // string cat operator

if (bb == "Bill Clinton") // boolean equal to operator
cout << "bb is equal to 'Bill Clinton' " << endl;

if (bb != "Al Gore") // boolean 'not equal' to operator
cout << "bb is not equal to 'Al Gore'" << endl;

62 Functions
The Iunctions provided by String class has the same name as that oI Java language's
String class. The Iunction names and the behaviour is exactly same as that oI Java's
String class. StringBuIIer class is also provided. This will Iacilitate portability oI code
between Java and C (you can cut and paste and do minimum changes to code). The
code Irom Java's Iunction body can be copied into C member Iunction body and
with very mininum changes the code will compile under C. Another advantage is
that developers coding in both Java and C do not need to remember two diIIerent
syntax or Iunction names.
For example to convert integer to string do -

String aa;

aa = 34; // The '=' operator will convert int to string
cout << "The value of aa is : " << aa.val() << endl;

aa = 234.878; // The '=' operator will convert float to string
cout << "The value of aa is : " << aa.val() << endl;

aa = 34 + 234.878;
cout << "The value of aa is : " << aa.val() << endl;
// The output aa will be '268.878'

// You must cast String to convert
aa = (String) 34 + " Can create infinite number of universes!! " +
234.878;
cout << "The value of aa is : " << aa.val() << endl;
// The output aa will be '34 Can create infinite number of
universes!! 234.878'

ReIer to Appendix A String.h Ior details about the String class Iunction names. The
same Iile String.h is reproduced here in next section.
7 Stringh file
In C (or any object oriented language), you just read the "class data-structure" (i.e.
interIace) to begin using that object. ou just need to understand the interIace and not
the implementation oI the interIace. In case oI String class, you just need to read and
understand the String class in String.h Iile. ou do not need to read the entire
implementation (String.cpp) in order to use String class. The object oriented classes
are real time saver and they very neatly hide the implementation.
(In object oriented Java language there is the equivalent called 'interface' , which
hides the implementation details.)
Given below is Stringh Iile and see also Appendix A String.h

//
// Author : Al Dev Email: alavoor@yahoo.com
// Use string class or String class
//
// To prevent memory leaks - a char class to manage character variables
// Always prefer to use String or string class
// instead of char, or char
//

#ifndef __STRING_H_ALDEV_
#define __STRING_H_ALDEV_

// do not use iostream as program becomes bulky..
#ifdef NJT_MSWINDJWS
#include <iostream
#else
#include <iostream.h // some compilers like .h here. Why...
#endif // NJT_MSWINDJWS

#include <stdio.h // for FILE and sprintf()
//#include <list.h // for list

// For MS Windows 95 VC++ or Borland C++ compiler do -
//see file d:\program files\CBuilder\include\examples\stdlib\list.cpp and
include\list.h
//#include <list // for list
//using namespace std;

const short INITIAL_SIZE = 50;
const short NUMBER_LENGTH = 300;
const int MAX_ISTREAM_SIZE = 2048;

//class StringBuffer;

// I compiled and tested this string class on Linux (Redhat 7.1) and
// MS Windows Borland C++ version 5.2 (win32). This should also work
// using MS Visual C++ compiler
class String
,
public:
String();
String(const char bb,); // needed by operator+
String(const char bb,, int start, int slength); // subset of
chars
String(int bb); // needed by operator+
String(unsigned long bb); // needed by operator+
String(long bb); // needed by operator+
String(float bb); // needed by operator+
String(double bb); // needed by operator+
String(const String & rhs); // Copy Constructor needed by
operator+
//String(StringBuffer sb); // Java compatibility - but
causes compile problem on MS windows and core dumps
String(int bb, bool dummy); // for StringBuffer class
virtual ~String(); // Made virtual so that when base class
is deleted
// then the derived
class destructor is called.

char val() ,return sval;, // It is not safe to make sval
public

// Functions below imitate Java language's String object
unsigned long length();
char charAt(int where);
void getChars(int sourceStart, int sourceEnd,
char target,, int targetStart);
char toCharArray();
char getBytes();

bool equals(String str2); // See also == operator
bool equals(char str2); // See also == operator
bool equalsIgnoreCase(String str2);

bool regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars);
bool regionMatches(bool ignoreCase, int startIndex,
String str2, int str2StartIndex, int
numChars);

String toUpperCase();
String toLowerCase();

bool startsWith(String str2);
bool startsWith(char str2);

bool endsWith(String str2);
bool endsWith(char str2);

int compareTo(String str2);
int compareTo(char str2);
int compareToIgnoreCase(String str2);
int compareToIgnoreCase(char str2);

int indexJf(char ch, int startIndex = 0);
int indexJf(char str2, int startIndex = 0);
int indexJf(String str2, int startIndex = 0);

int lastIndexJf(char ch, int startIndex = 0);
int lastIndexJf(char str2, int startIndex = 0);
int lastIndexJf(String str2, int startIndex = 0);

String substring(int startIndex, int endIndex = 0);
String replace(char original, char replacement);
String replace(char original, char replacement);

String trim(); // See also overloaded trim()

String concat(String str2); // See also operator +
String concat(char str2); // See also operator +
String concat(int bb);
String concat(unsigned long bb);
String concat(float bb);
String concat(double bb);

String reverse(); // See also overloaded reverse()
String deleteCharAt(int loc);
String deleteStr(int startIndex, int endIndex); // Java's
"delete()"

String valueJf(char ch)
,char aa2,; aa0,=ch; aa1,=0; return String(aa);,
String valueJf(char chars,), return String(chars);,
String valueJf(char chars,, int startIndex, int numChars);
String valueJf(bool tf)
,if (tf) return String("true"); else return
String("false");,
String valueJf(int num), return String(num);,
String valueJf(long num), return String(num);,
String valueJf(float num) ,return String(num);,
String valueJf(double num) ,return String(num);,

// See also StringBuffer class in this file given below

// ---- End of Java like String object functions -----

//////////////////////////////////////////////////////
// List of additonal functions not in java
//////////////////////////////////////////////////////
String ltrim();
void ltrim(bool dummy); // Directly changes object. dummy to
get different signature
String rtrim();
void rtrim(bool dummy); // Directly changes object. See also
chopall().
// dummy to get different signature

void chopall(char ch='\n'); // removes trailing character
'ch'. See also rtrim()
void chop(); // removes one trailing character

void roundf(float input_val, short precision);
void decompose_float(long integral, long fraction);

void roundd(double input_val, short precision);
void decompose_double(long integral, long fraction);

void explode(char separator); // see also token() and
overloaded explode()
String explode(int & strcount, char separator = ' '); // see
also token()
void implode(char glue);
void join(char glue);
String repeat(char input, unsigned int multiplier);
String tr(char from, char to); // translate characters
String center(int padlength, char padchar = ' ');
String space(int number = 0, char padchar = ' ');
String xrange(char start, char end);
String compress(char list = " ");
String left(int slength = 0, char padchar = ' ');
String right(int slength = 0, char padchar = ' ');
String overlay(char newstr, int start = 0, int slength = 0,
char padchar = ' ');

String at(char regx); // matches first match of regx
String before(char regx); // returns string before regx
String after(char regx); // returns string after regx
String mid(int startIndex = 0, int length = 0);

bool isNull();
bool isInteger();
bool isInteger(int pos);
bool isNumeric();
bool isNumeric(int pos);
bool isEmpty(); // same as length() == 0
bool isUpperCase();
bool isUpperCase(int pos);
bool isLowerCase();
bool isLowerCase(int pos);
bool isWhiteSpace();
bool isWhiteSpace(int pos);
bool isBlackSpace();
bool isBlackSpace(int pos);
bool isAlpha();
bool isAlpha(int pos);
bool isAlphaNumeric();
bool isAlphaNumeric(int pos);
bool isPunct();
bool isPunct(int pos);
bool isPrintable();
bool isPrintable(int pos);
bool isHexDigit();
bool isHexDigit(int pos);
bool isCntrl();
bool isCntrl(int pos);
bool isGraph();
bool isGraph(int pos);

void clear();
int toInteger();
long parseLong();

double toDouble();
String token(char separator = ' '); // see also
StringTokenizer, explode()
String crypt(char original, char salt);
String getline(FILE infp = stdin); // see also putline()
//String getline(fstream infp = stdin); // see also
putline()

void putline(FILE outfp = stdout); // see also getline()
//void putline(fstream outfp = stdout); // see also
getline()

void swap(String aa, String bb); // swap aa to bb
String sort(String aa,); // sorts array of strings
String sort(int startIndex = 0, int length = 0); // sorts
characters inside a string
int freq(char ch); // returns the number of distinct,
nonoverlapping matches
void Format(const char fmt, ...);
String replace (int startIndex, int endIndex, String str);

void substring(int startIndex, int endIndex, bool dummy); //
Directly changes object
void reverse(bool dummy); // Directly changes object. dummy
to get different signature
String deleteCharAt(int loc, bool dummy); // Directly changes
object
String deleteStr(int startIndex, int endIndex, bool dummy);
void trim(bool dummy); // Directly changes object. dummy to
get different signature
String insert(int index, String str2);
String insert(int index, String str2, bool dummy); //
Directly changes object
String insert(int index, char ch);
String insert(int index, char ch, bool dummy); // Directly
changes object
String insert(char newstr, int start = 0, int length = 0,
char padchar = ' ');

String dump(); // Dump the string like 'od -c' (octal dump)
does

// required by java's StringBuffer
void ensureCapacity(int capacity);
void setLength(int len);
void setCharAt(int where, char ch); // see also charAt(),
getCharAt()

// required by java's Integer class, Long, Double classes
int parseInt(String ss) ,return ss.toInteger();,
int parseInt(char ss)
,String tmpstr(ss); return tmpstr.toInteger();,
long parseLong(String ss) ,return ss.parseLong();,
long parseLong(char ss)
,String tmpstr(ss); return tmpstr.parseLong();,
float floatValue() ,return (float) toDouble(); ,
double doubleValue() ,return toDouble(); ,
char number2string(int bb); // see also String(int)
char number2string(long bb); // see also String(long)
char number2string(unsigned long bb); // see also
String(long)
char number2string(double bb); // see also String(double)

///////////////////////////////////////////////
// List of duplicate function names
///////////////////////////////////////////////
// char c_str() // use val()
// bool find(); // Use regionMatches()
// bool search(); // Use regionMatches()
// bool matches(); // Use regionMatches()
// int rindex(String str2, int startIndex = 0); Use
lastIndexJf()
// String blanks(int slength); // Use repeat()
// String append(String str2); // Use concat() or + operator
// String prepend(String str2); // Use + operator. See also
append()
// String split(char separator = ' '); // Use token(),
explode() or StringTokenizer class
bool contains(char str2, int startIndex = 0); // use
indexJf()
// void empty(); Use is_empty()
// void vacuum(); Use clear()
// void erase(); Use clear()
// void zero(); Use clear()
// bool is_float(); Use is_numeric();
// bool is_decimal(); Use is_numeric();
// bool is_Digit(); Use is_numeric();
// float float_value(); Use toDouble();
// float tofloat(); Use toDouble();
// double double_value(); Use toDouble();
// double numeric_value(); Use toDouble();
// int int_value(); Use toInteger()
// int tonumber(); Use toInteger()
// String get(); Use substring() or val() but prefer java's
substring
// String getFrom(); Use substring() or val() but prefer
java's substring
// String head(int len); Use substring(0, len)
// String tail(int len); Use substring(length()-len,
length())
// String cut(); Use deleteCharAt() or deleteStr()
// String cutFrom(); Use deleteCharAt() or deleteStr()
// String paste(); Use insert()
// String fill(); Use replace()
// char firstChar(); // Use substring(0, 1);
// char lastChar(); // Use substring(length()-1, length());
// String findNext(); Use token(), explode() or
StringTokenizer class

// begin(); iterator. Use operator ii,
// end(); iterator. Use operator ii,
// copy(); Use assignment = operator, String aa = bb;
// clone(); Use assignment = operator, String aa = bb;
// void putCharAt(int where, char ch); Use setCharAt()
// void replaceCharAt(int where, char ch); Use setCharAt()
// char getCharAt(int where); Use CharAt()
// void parseArgs(int where, char ch); Use StringTokensizer
class, token() or explode()
// void truncate(); Use trim(), rtrim(), chop() or chopall()
// convert number to string notostring(), int2str, long2str
Use number2string()

// All Jperators ...
String operator+ (const String & rhs);
friend String operator+ (const String & lhs, const String &
rhs);

String& operator+= (const String & rhs); // using reference
will be faster
String& operator= (const String & rhs); // using reference
will be faster
bool operator== (const String & rhs); // using reference will
be faster
bool operator== (const char rhs);
bool operator!= (const String & rhs);
bool operator!= (const char rhs);
char operator , (unsigned long Index) const;
char& operator , (unsigned long Index);
friend ostream & operator<< (ostream & Jut, const String &
str2);
friend istream & operator (istream & In, String & str2);

//do later: static list<String
explodeH; // list head

protected:
char sval; // Not safe to make sval public
void verifyIndex(unsigned long index) const; // not "inline"
because MS Win32 complains
void verifyIndex(unsigned long index, char aa) const;// not
"inline" - MS Win32 complains

void _str_cat(char bb,);
void _str_cat(int bb);
void _str_cat(unsigned long bb);
void _str_cat(float bb);

void _str_cpy(char bb,);
void _str_cpy(int bb); // itoa
void _str_cpy(unsigned long bb);
void _str_cpy(float bb); // itof

private:
// Note: All the private variables and functions begin
// with _ (underscore)

//static String _global_String; // for use in add operator
//inline void _free_glob(String aa);

bool _equalto(const String & rhs, bool type = false);
bool _equalto(const char rhs, bool type = false);
String _pString; // temporary pointer for internal use..
char _pNumber2String; // temporary pointer for internal
use..
inline void _allocpString();
inline void _allocpNumber2String();
inline void Common2AllCstrs();
inline void _reverse();
inline void _deleteCharAt(int loc);
inline void _deleteStr(int startIndex, int endIndex);
inline void _trim();
inline void _ltrim();
inline void _rtrim();
inline void _substring(int startIndex, int endIndex);
void _roundno(double input_dbl, float input_flt, short
precision, bool type);
,;

// Global variables are defined in String.cpp

#endif // __STRING_H_ALDEV_

7 StringBufferh

//
// Author : Al Dev Email: alavoor@yahoo.com
//

#ifndef __STRINGBUFFER_H_ALDEV_
#define __STRINGBUFFER_H_ALDEV_

// Imitate Java's StringBuffer object
// This class is provided so that the Java code is
// portable to C++, requiring minimum code changes
// Note: While coding in C++ DJ NJT use this class StringBuffer,
// this is provided only for compiling code written in Java
// which is cut/pasted inside C++ code.
class StringBuffer: public String
,
public:
StringBuffer();
~StringBuffer();
StringBuffer(char aa);
StringBuffer(int size);
StringBuffer(String str);

int capacity();
StringBuffer append(String str2);
// See also operator +
//, this += str2; return this;, // This is causing
core dumps...

StringBuffer append(char str2);
StringBuffer append(int bb);
StringBuffer append(unsigned long bb) ;
StringBuffer append(float bb) ;
StringBuffer append(double bb) ;

StringBuffer insert(int index, String str2);
StringBuffer insert(int index, char ch);

StringBuffer reverse();

// Java's "delete()". Cannot use name delete in C++
StringBuffer deleteStr(int startIndex, int endIndex);
StringBuffer deleteCharAt(int loc);

StringBuffer substring(int startIndex, int endIndex = 0);
void assign(char str);

private:
StringBuffer _pStringBuffer;
inline void allocpStringBuffer();
inline void Common2AllCstrs();
,;

#endif // __STRINGBUFFER_H_ALDEV_

72 StringTokenizerh

//
// Author : Al Dev Email: alavoor@yahoo.com
//

#ifndef __STRINGTJKENIZER_H_ALDEV_
#define __STRINGTJKENIZER_H_ALDEV_

// Imitate java's StringTokenizer class
// provided to compile java code in C++ and vice-versa
class StringTokenizer: public String
,
public:
StringTokenizer(String str);
StringTokenizer(String str, String delimiters);
StringTokenizer(String str, String delimiters, bool
delimAsToken);
~StringTokenizer();

int countTokens();
bool hasMoreElements();
bool hasMoreTokens();
String nextElement(); // in java returns type 'Jbject'
String nextToken();
String nextToken(String delimiters);
private:
int CurrentPosition; // current index on string
int TotalTokens;
int RemainingTokens;
char ListJfDl; // list of delimiters
char WorkStr; // temp work string
char JrigStr; // original string passed
bool DlFlag; // delimiter flag
inline void vPrepWorkStr(char delimiters = NULL);
,;

#endif // __STRINGTJKENIZER_H_ALDEV_
8 Renaming the String class
8 Case : Simple rename
II you do not like the String class name then you can use "typedef" to rename the
String class.
In all the Iiles where you do include String.h, insert these lines:

// If you do not like the class name String, then you can rename using
typedef
typedef String StringSomethingElseIwant;

// Your remaing code may be like this ....
int main()
,
StringSomethingElseIwant aa_renstr;
aa_renstr = "I renamed the String Class using typedef";

.......etc...
,

See Lhe example_SLrlngcpp
82 Case 2: Resolve conflict
II there is a conIlict with another class-name having the same name, and you want to
use both this class and conIlicting class then you use this technique - in all the Iiles
where you do include String.h, insert these lines:

#define String String_somethingelse_which_I_want
#include "String.h"
#undef String

#include "ConflictingString.h" // This also has String class...

// All your code goes here...
main()
,
String_somethingelse_which_I_want aa;
String bb; // This string class from conflicting string class

aa = " some sample string";
bb = " another string abraka-dabraka";
.......
,

1he preprocessor wlll replace all llLerals of SLrlng Lo
SLrlng_someLhlngelse_whlch_l_wanL and lmmdlaLely undeflnes SLrlng AfLer undef
Lhe confllcLlng sLrlng class header flle ls lncluded whlch deflnes Lhe SLrlng class

9 File Class
ou would use the File class to manipulate the operating system Iiles. This class is an
imitation oI Java's File class and will be very useIul in C programming. Using this
File class in C you can do iI Iile exists() ?, iI directory exists() ?, Iile length() and
other Iunctions.
O C++ llle class ls aL
llleh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/llleh and
lllecpphLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/lllecpp
O !ava [avalollle class
deflnlLlon hLLp//[avasuncom/[2se/13/docs/apl/[ava/lo/lllehLml
O Culck 8eference on llle
Class hLLp//unlcornsresLorg/reference/[ava/qref11/[avalolllehLml
O llle Class summary hLLp//wwwldlnLnuno/daLabase/Sll8020/[ava
apl/[avalolllehLml

C++ Zap (Delete) function
The delete and new operators in C are much better than the malloc and Iree
Iunctions oI C. Consider using new and zap (delete Iunction) instead oI malloc and
Iree as much as possible.
To make delete operators even more cleaner, make a Zap() inline Iunction. DeIine a
zap() Iunction like this:

// Put an assert to check if x is NULL, this is to catch
// program "logic" errors early. Even though delete works
// fine with NULL by using assert you are actually catching
// "bad code" very early

// Defining Zap using templates
// Use zap instead of delete as this will be very clean
template <class T
inline void zap(T & x)
,
,assert(x != NULL);,
delete x;
x = NULL;
,

// In C++ the reason there are 2 forms of the delete operator is - because
// there is no way for C++ to tell the difference between a pointer to
// an object and a pointer to an array of objects. The delete operator
// relies on the programmer using "," to tell the two apart.
// Hence, we need to define zaparr function below.
// To delete array of pointers
template <class T
inline void zaparr(T & x)
,
,assert(x != NULL);,
delete , x;
x = NULL;
,

The zap() Iunction will delete the pointer and set it NULL. This will ensure that even
iI multiple zap()'s are called on the same deleted pointer then the program will not
crash. Please see the Iunction zapexample() in exampleString.cpp.

// See zap_example() in example_String.cpp
zap(pFirstname);
//zap(pFirstname); // no core dumps. Because pFirstname is NULL now
//zap(pFirstname); // no core dumps. Because pFirstname is NULL now

zap(pLastname);
zap(pJobDescription);

int iiarray = new int10,;
zaparr(iiarray);

There is nothing magical about this, it just saves repetative code, saves typing time
and makes programs more readable. The C programmers oIten Iorget to reset the
deleted pointer to NULL, and this causes annoying problems causing core dumps and
crashes. The zap() takes care oI this automatically. Do not stick a typecast in the zap()
Iunction -- iI something errors out on the above zap() Iunction it likely has another
error somewhere.
Also mymalloc() , myrealloc() and myIree() should be used instead oI malloc(),
realloc() and Iree(), as they are much cleaner and have additional checks. For an
example, see the Iile "String.h" which is using the mymalloc() and myIree()
Iunctions.
WARNING : Do not use Iree() to Iree memory allocated with 'new' or 'delete' to Iree
memory allocated with malloc. II you do, then results will be unpredictable.
See the zap examples in exampleString.cpp.
Pointers are problems
Pointers are not required Ior general purpose programming. In modern languages like
Java there is no support Ior pointers (Java internally uses pointers). Pointers make the
programs messy and programs using pointers are very hard to read.
Avoid using pointers as much as possible and use reIerences. Pointers are really a
great pain. It is possible to write an application without using pointers. You should
pointers only in those cases where references will not work.
A reference is an alias; when you create a reIerence, you initialize it with the name oI
another object, the target. From the moment on, the reIerence acts as an alternative
name oI the target, and anything you do to the reIerence is really done to the target.
Syntax of References: Declare a reIerence by writing the type, Iollowed by the
reIerence operator (&), Iollowed by the reIerence name. ReIerences MUSTbe
initialized at the time oI creation. For example -

int weight;
int & rweight = weight;

DJG aa;
DJG & rDogRef = aa;

os oI reIerences -
O Do use reIerences to create an alias to an object
O Do initialize all reIerences
O Do use reIerences Ior high eIIiciency and perIormance oI program.
O Do use const to protect reIerences and pointers whenever possible.
o nots oI reIerences -
O IMPORTANT: Don't use reIerences to NULL objects
O Don't conIuse the address oI operator & with reIerence operator. The reIerences
are used in the declarations section (see Syntax oI ReIerences above).
O Don't try to reassign a reIerence
O Don't use pointers iI reIerences will work
O Don't return a reIerence to a local object
O Don't pass by reIerence iI the item reIerred to may go out oI scope
2 Usage of my_malloc and my_free
Try to avoid using malloc and realloc as much as possible and
use new and zap(delete). But sometimes you may need to use the "C" style memory
allocations in "C". Use the Iunctions my_malloc() , my_realloc() and my_free().
These Iunctions do proper allocations and initialisations and try to prevent memory
problems. Also these Iunctions (in DEBUG mode) can keep track oI memory
allocated and print total memory usage beIore and aIter the program is run. This tells
you iI there are any memory leaks.
The mymalloc and myrealloc is deIined as below. It allocates little more memory
(SAFEMEM 5) and initializes the space and iI it cannot allocate it exits the
program. The 'callcheck(), removeptr()' Iunctions are active only when
DEBUGMEM is deIined in makeIile and are assigned to ((void)0) i.e. NULL Ior
non-debug production release. They enable the total-memory used tracing.

void local_my_malloc(size_t size, char fname,, int lineno)
,
size_t tmpii = size + SAFE_MEM;
void aa = NULL;
aa = (void ) malloc(tmpii);
if (aa == NULL)
raise_error_exit(MALLJC, VJID_TYPE, fname, lineno);
memset(aa, 0, tmpii);
call_check(aa, tmpii, fname, lineno);
return aa;
,

char local_my_realloc(char aa, size_t size, char fname,, int lineno)
,
remove_ptr(aa, fname, lineno);
unsigned long tmpjj = 0;
if (aa) // aa != NULL
tmpjj = strlen(aa);
unsigned long tmpqq = size + SAFE_MEM;
size_t tmpii = sizeof (char) (tmpqq);
aa = (char ) realloc(aa, tmpii);
if (aa == NULL)
raise_error_exit(REALLJC, CHAR_TYPE, fname, lineno);

// do not memset memset(aa, 0, tmpii);
aatmpqq-1, = 0;
unsigned long kk = tmpjj;
if (tmpjj tmpqq)
kk = tmpqq;
for ( ; kk < tmpqq; kk++)
aakk, = 0;
call_check(aa, tmpii, fname, lineno);
return aa;
,

See my_malloccpp and Lhe header flle my_malloch for full lmplemenLaLlon of Lhe
my_malloc program
An example on usage oI mymalloc and myIree as below:

char aa;
int bb;
float cc;
aa = (char ) my_malloc(sizeof(char) 214);
bb = (int ) my_malloc(sizeof(int) 10);
cc = (float ) my_malloc(sizeof(int) 20);

aa = my_realloc(aa, sizeof(char) 34);
bb = my_realloc(bb, sizeof(int) 14);
cc = my_realloc(cc, sizeof(float) 10);

noLe LhaL ln my_realloc you do noL need Lo casL Lhe daLaLype as Lhe varlable lLself ls
passed and correcL my_realloc ls called whlch reLurns Lhe proper daLaLype polnLer
1he my_realloc has overloaded funcLlons for char* lnL* and floaL*
2 Garbage Collector for C++
In C/C Garbage Collection is not a standard Ieature and hence allocating and
Ireeing storage explicitly is diIIicult, complicated and is error-prone. TheGarbage
Collection (GC) is not part oI the C standard because there are just so many ways
how one could implement it; there are many GC techniques, and deciding to use a
particular one would not be good Ior certain programs. Computer scientists had
designed many GC algorithms, each one oI them catering to a particular problem
domain. There is no one single generic GC which will tackle all the problem domains.
As a consequence, GC is not part oI C standard, they just leIt it out. Still, you
always have the choice oI many Ireely available C libraries that do the job Ior you.
Visit the C Garbage Collection and Memory management site.
3 Debug files
To debug any C or C programs include the Iile debug.h and in your 'MakeIile'
deIine DEBUGSTR, DEBUGPRT, DEBUGMEM to turn on the traces Irom the
debug.h Iunctions. When you remove the '-DDEBUGSTR' etc.. then the debug
Iunction calls are set to ((void)0) i.e. NULL, hence it has no impact on Iinal
production release version oI project. ou can generously use the debug Iunctions in
your programs and it will not increase the size oI production executable.
See the Iile debug.cpp Ior implementation oI debug routines. And see the
Iile mymalloc.cpp Ior sample which uses debug.h and debug Iunctions.
See the sample MakeIile .
4 1ava like API
Visit the Iollowing sites Ior Java like API Ior C
O !ava uLlls ln C++ hLLp//wwwpulsarorg/users/e[/archlve/oop
O hu 1hesls book !ava Al ln C++ hLLp//wwwpulsarorg/archlve/phd/e[phd
5 IDE tools for C++
The Iollowing IDE tools (Integrated Development Environment) are available Ior
C:
O 1he Lop raLed uevC++ ls an fullfeaLured lnLegraLed uevelopmenL
LnvlronmenL (luL) for boLh Wln32 and Llnux lL uses CCC Mlngw or Cygwln as
compller and llbrarles seL lL ls aL hLLp//wwwbloodshedneL/devcpphLml and
aL mlrrorslLe
O kuL kdevelop
O 8laLura slLe C++ 1ools
O AmuleL AmuleL
O App uev sulLe Angoss
O Make replacemenL 8rass
O S/W producL meLrlcs CCC
O ro[ecL mgmL edlL complle debug Clorge
O uev envlronmenL Code Crusader
O Craphlc gdb Code Medlc
O Code analysls CodeWlzard
O Cen P1ML La1ex for C++ cod uoc C++
O Cul LoolklL openCL lLk
O C++ and !ava luL CLC luL
O P luL P Lloquence
O luL C++ !ava ascal 8PluL
O luL for C++ !ava Snlff
O luL for C++ !ava WlpeouL
O xbased dev env xWL
6 C++ Online Textbooks and Docs
O C++ AnnoLaLlons onllne book maln slLe AnnoLaLlons beLLer slLe mlrrorslLe
O 1each ?ourself C++ ln 21 days onllne LexLbook 1each C++
O C++ Cnllne 1exLbook C++ 8ruce Lckel
O C++ Cpen books anorama and cllck on Cpen 8ooks
O Whos Afrald of C++? onllne LexLbook SLeveheller
O lnLroducLlon Lo Cb[ecL CrlenLed rogrammlng an ebook C++ CC
O C++ ln PyperLexL C++ PyperLexL
O Cb[ecL CrlenLed SysLems CC arLlcle
O orLlng C++ Lo !ava orLlngC
O C/C++ !ournals uLah!ournals
O ?ahoo C++ caLegory slLe CCyahoo
O C Llbrary 8eference Culde c_gulde
O Cnllne LexLbooks C++/!ava lreeLlb
Java books which will be useIul Ior C programmers:
O CreaL Web reference slLe Web8ef
O Many [ava books !8ooks
O lnLro Lo !ava v30 !avanoLes mlrror !avanoLes
O Web Llbrary hLLp//wwwlLllbrarycom
O lnLermedlaLe Level !ava book hLLp//wwwbruceeckelcom
O 1hlnklng ln !ava 1hlnklng C++
O !ohn Popklns unlv !ava resources Pall
O onllne [ava LuLorlal ChorLle
O racLlcal gulde for !ava Sun8ooks
O !ava SoLon
7 C++ Coding Standards
Coding standard is very essential Ior readability and maitainence oI programs. And it
also greatly inproves the productivity oI the programmer. The GNU C
compiler must enforce coding discipline. The Iollowing is suggested - inside class
deIinition:
O All publlc varlables musL begln wlLh m llke mIooVar 1he m sLands
for membet
O All proLecLed varlables musL begln wlLh mt llke mtIooVar and meLhods wlLh L
llke tIooNum() 1he t sLands for ptotecteJ
O All prlvaLe varlables musL begln wlLh mv llke mvIooVar and meLhods wlLh v
llke vIooLone() 1he v sLands for ptlvote
O All publlc proLecLed and prlvaLe varlables musL begln wlLh uppercase
afLer m llke l ln mIooVar
O All polnLer varlables musL be preflxed wlLh p llke
o ubllc varlables mpIooVar and meLhods llke loonum()
o roLecLed varlables mtpIooVar and meLhods wlLh L llke Lloonum()
o rlvaLe varlables mvpIooVar and meLhods wlLh v llke vloonum()
1he compller should generaLe error lf Lhe code does noL follow above sLandard 1he
C++ compller can provlde a flag opLlon Lo bypass sLrlcL codlng sLandard Lo complle
old source code and for all new code belng developed wlll follow Lhe unlform world
wlde codlng sLandard
In the sample code given below t stands Ior protected, v stands Ior private, m stands
Ior member-variable and p stands Ior pointer.

class SomeFunMuncho
,
public:
int mTempZimboniMacho; // Jnly temporary variables should
be public as per JJP
float mpTempArrayNumbers;
int HandleError();
float getBonyBox(); // Public accessor as per JJP design
float setBonyBox(); // Public accessor as per JJP design
protected:
float mtBonyBox;
int mtpBonyHands;
char tHandsFull();
int tGetNumbers();
private:
float mvJustDoIt;
char mvFirstName30,;
int mvpTotalValue;
char vSubmitBars();
int vGetNumbers();
,;

When your program grows by mllllons of llnes of code Lhen you wlll greaLly
appreclaLe Lhe namlng convenLlon as above 1he readablllLy of code lmproves
because [usL by looklng aL Lhe varlable name llke mvI|rstName you can Lell LhaL lL ls
member of a class and ls a prlvaLe varlable
Visit the C Coding Standards URLs
O C++ lAC LlLe Codlng sLandards hLLp//new
brunswlckneL/workshop/c++/faq/codlngsLandardshLml
O 8lce unlverslLy codlng
sLandard hLLp//wwwcsrlceedu/dwallach/CluslusSLylehLml
O ldenLlflers Lo avold ln C++
rograms hLLp//oakroadsysLemscom/Lech/cppredefhLm
O Codlng sLandards from
osslblllLy hLLp//wwwposslblllLycom/Cpp/CppCodlngSLandardhLml and mlrr
or slLe
O Codlng sLandards for !ava and C++ from
AmbysofL hLLp//wwwambysofLcom/[avaCodlngSLandardshLml
O 8ules and recommendaLlons hLLp//wwwcsumdedu/users/cml/csLyle/
O lndenL and annoLaLe hLLp//wwwcsumdedu/users/cml/csLyle/lndhlll
annoLhLml
O LlemenLal rules hLLp//wwwcsumdedu/users/cml/csLyle/LllemLelruleshLml
O C++ sLyle doc hLLp//wwwcsumdedu/users/cml/csLyle/Wlldflre
C++SLylehLml
O C++ Codlng SLandards by 8reLL
Scolcum hLLp//wwwskypolnLcom/slocum/prog/cppsLdshLml
O Loglkos C++ Codlng
SLandards hLLp//wwwloglkoscom/sLandards/cpp_sLdhLml
O n8ad C++ codlng
sLandards hLLp//cadswescoloradoedu/blllo/sLandards/nrad
O 8L!uC C++ codlng sLandards hLLp//wwwmeurrensorg/lp
Llnks/[ava/[oodcs/1oddPoffhLml
O ArcLlc Labs codlng sLandards hLLp//wwwarcLlclabscom/codlngsLandards
See also
O lor rapld navlgaLlon wlLh cLags vlm color LexL edlLor
O 1o lmprove producLlvlLy see C++ 8eauLlfler PCW1C
8 C++ Online Docs
There are MORE THAN ONE MILLION online articles/textbooks/reIerence guides
on C language. That is because C is used extensively Ior a very long period oI
time. ou can Iind them using the Internet search engines like ahoo, Lycos, Excite
etc..
Visit the Iollowing C sites :-
O C++ S1L baslc sLrlng
class hLLp//wwwsglcom/1echnology/S1L/baslc_sLrlnghLml
O See Lhe secLlon S1L 8eferences
O C++ Crashproof slLe hLLp//wwwLroubleshooLerscom/codecorn/crashprfhLm
O C++ Memory slLe hLLp//wwwLroubleshooLerscom/codecorn/memleakhLm
O Cnu Maln slLe hLLp//wwwgnuorg and gnu C++ slLe
aL hLLp//wwwgnuorg/sofLware/gcc/gcchLml
O Cnu C++ Llbrary
socs hLLp//wwwsocsuLseduau/doc/gnulnfo/llbg++/llbg++_18hLml
O Cnu C++ Llbrary gsl hLLp//wwwgslde/doc/gnu/llbg++_LochLml
O Cnu C++ Llbrary
Lechno hLLp//wwwLechnospbru/xbaLob/lAC/Cnu/llbg++_LochLml
O Cnu C++ Llbrary uLah hLLp//wwwmaLhuLahedu/docs/lnfo/llbg++_LochLml
O AS unlverslLy C++ SLandard SLrlng
class hLLp//wwweasasuedu/cse200/ouLllne
O !ava !SLrlng for
C++ hLLp//wwwmlke93com/c_plusplus/classes/!SLrlng/!SLrlng_cppasp
O C++ Language 8eference hLLp//wwwmsoeedu/LrlLL/cpplanghLml
O C++ rogram examples and
samples hLLp//wwwmsoeedu/LrlLL/cpp/exampleshLml
O nells C++ sLuff hLLp//wwwcyclone7com/cpp
Internet has vast amounts oI documentation on C. Visit the search engines like
ahoo, Lycos, InIoseek, Excite. Type in the keywords 'C++ tutorials' 'C++
references' 'C++ books' . ou can narrow down the search criteria by clicking
on Advanced search and select search by exact phrase
O hLLp//wwwyahoocom
O hLLp//wwwlycoscom
O hLLp//wwwlnfoseekcom
O hLLp//wwwexclLecom
O hLLp//wwwmammacom
8 C++ Tutorials
There are many on-line tutorials available on internet. Type 'C tutorials' in the
search engine.
O C++ 1uLorlal hLLp//wwwxplolLercom/programmlng/c/lndexshLml
O C++ 1uLorlal llSc
lndla hLLp//wwwcsallscerneLln/uocumenLaLlon/1uLorlals/SLyleCuldes/c++
sLylehLml
O C++ 1uLorlal 8rown
unlv hLLp//wllmacsbrownedu/courses/cs032/resources/C++LuLorlalhLml
O C++ 1uLorlal hLLp//homemsullLeduph/ddd/LuLorlals/cpp/cppllsLhLm
O C++ 1uLorlal
lCsLreams hLLp//oslrlssunderlandacuk/cs0pdu/pub/com363/Sched3/locpp
hLml
82 Useful links
Bird's eye view oI C URLs (about 153 url
links) http://www.enteract.com/~bradapp/links/cplusplus-links.html
This URL: http://www.snippets.org portable C code contains over 360 Iiles.
83 C++ Quick-Reference
Type 'C ReIerence' in the search engine.
O C++ qulck ref hLLp//wwwcs[cueduau/davld/C++S?n1AxhLml
O C++ SLandard Llbrary Culck
8eference hLLp//wwwhalpernwlghLsofLwarecom/sLdllb
scraLch/qulckrefhLml
O C++ S1L from halper hLLp//wwwhalpernwlghLsofLwarecom/sLdllb
scraLch/qulckrefhLml
84 C++ Usenet Newsgroups
O C++ newsgroups complangc++announce
O C++ newsgroups complangc++*
O C++ newsgroups hLLp//marshallcllnehomeaLLneL/cppfaqllLe
9 Memory Tools
Use the Iollowing memory debugging tools
O 1he ,atro| ls a very powerful memory debugglng Lool lL ls
aL hLLp//wwwcbmamlgademoncouk/mpaLrol and
aL hLLp//wwwrpmflndneL go here and search mpaLrol lf you are uslng llnux
Lhen you musL download Lhe mpaLrol*srcrpm flle from Lhe rpmflndneL 1o
updaLe Lhe mpaLrol*srcrpm Lo laLesL verslon you can use Lhe old
mpaLrolspec flle and laLesL mpaLrol*Largz flle Lo rebulld new *srcrpm
O Cn llnux conLrlb cdrom see mem_LesL*rpm package and
aL hLLp//wwwrpmflndneL go here and search mem_LesL
O Cn llnux cdrom see LlecLrlclence*rpm package and
aL hLLp//wwwrpmflndneL go here and search elecLrlcfence
O urlfy 1ool from 8aLlonal SofLware Corp hLLp//wwwraLlonalcom
O lnsure++ 1ool from arasofL Corp hLLp//wwwparasofLcom
O Llnux 1ools aL hLLp//wwwxneLcom/blaLura/llnapp6hLml#Lools
O Search Lhe lnLerneL englnes llke ?ahoo Lycos LxclLe Mammacom for
keyword Llnux memory debugglng Lools
2 Related URLs
ou MUST use a color editor like 'Vim' (Vi improved) while coding in C. Color
editors greatly increase your productivity. Visit the URL Ior Vim howto below.
Visit Iollowing locators which are related to C, C -
O vlm color LexL edlLor for C++ C hLLp//meLalabuncedu/Lu/PCW1C/vlm
PCW1ChLml
O C++ 8eauLlfler PCW1C hLLp//meLalabuncedu/Lu/PCW1C/CC++8eauLlfler
PCW1ChLml
O Source code conLrol sysLem for C++ programs (CvS
PCW1C) hLLp//meLalabuncedu/Lu/PCW1C/CvSPCW1ChLml
O Llnux goodles maln slLe ls aL hLLp//wwwaldev8mcom Mlrror slLes are aL
hLLp//aldev0web[umpcom angelflre geoclLles vlrLualave 30megs Lheglob
en8Cl 1errashare lorLuneclLy lreewebslLes 1rlpod Spree Lscallx PLLpclLy
lreeservers
2 C++ Scripting Languages
The major disadvantage oI C is that you must recompile and link the object Iiles to
create a executable anytime you make a small change. The compile/link/debug cycles
take away a lot oI time and is quite unproductive. Since modern CPU's and RAM are
becoming extremely Iast and cheap, it is better to spend more money on hardware and
use scripting languages Ior development.
2 PIKE (C/C++ Scripting Language)
The scripting language like PIKE eliminates the linking and re-compiling and will
really speed up the development process.
As memory (RAM) prices are dropping and CPU speeds are increasing, scripting
language like PIKE will EXPLODE in popularity. PIKE will become most widely
used scripting language as it is object oriented and it's syntax is very identical to that
oI C language.
Programming productivity will increase by five times by using the Pike C scripting
language. And Pike is very useIul Ior 'prooI oI concept' and developing prototypes
rapidly.
The Pike is at http://pike.roxen.com and at http://www.roxen.com.
The Roxen Web server is completely written in Pike, which demonstrates how
powerIul Pike is. Pike runs much Iaster than Java Ior some operations and is quite
eIIicient in using memory resources.
22 SoftIntegration Ch (C/C++ Scripting Language)
II you want commercial scripting language, get the 'Ch scripting' product Irom
SoItIntegration corporation at http://www.soItintegration.com.
The scripting language environment called Ch is a superset oI C with high-level
extensions, and salient Ieatures Irom C and other languages so that users can learn
the language once and use it anywhere Ior almost any programming purposes. This C-
compatible scripting language environment is also a middleware serving as crucial
soItware inIrastructure Ior running portable applications in heterogeneous platIorms.
The portable Ch code can be deployed saIely over the internet or intranets to run
anywhere ranging Irom supercomputers, workstations, PCs, Palm Pilots, PDA, to non-
traditional computing devices such as CNC machines, robots, TVs, reIrigerators,
among others.
23 PHP (C++ Scripting Language)
PHP is hypertext-preprocessor scripting language and is very rapidly evolving and
getting object oriented Ieatures. It has the "class" keyword through which it tries to
implement object oriented scripting. May be in near Iuture PHP will mature rapidly to
become a robust scripting language Ior object oriented projects. In Iuture it will tackle
both the web applications and general purpose applications. Why have diIIerent
scripting languages Ior web and general applications, instead just use PHP Ior both.
PHP is at http://www.linuxdoc.org/HOWTO/PHP-HOWTO.html.
22 Templates
O hLLp//babbagecsqcedu/S1L_uocs/LemplaLeshLm Mlrror
aL hLLp//wwwmlke93com/c_plusplus/LuLorlal/LemplaLes
O 1hls Lells abouL #pragma LemplaLe
hLLp//wwwdgpLoronLoedu/people/!amesSLewarL/270/9697f/noLes/nov23
LuLhLml
O very CCCu slLe hLLp//wwwcpluspluscom/doc/LuLorlal/LuL3
1hLml hLLp//wwwcpluspluscom/doc/LuLorlal
O lor cerLlflcaLlon of C++ goLo hLLp//examwarecom and cllck on 1uLorlals
and Lhen C/C++ buLLon
O C++ Cpen books hLLp//wwwsofLpanoramaorg/Lang/cppshLml and cllck on
LuLorlals
O 1emplaLes LuLorlal
hLLp//wwwlnfosysLuwlenacaL/8esearch/ComponenL/LuLorlal/prwmalnhL
m
23 STL References
Please visit the Iollowing sites Ior STL -
O very good lnLro Lo
lLeraLors hLLp//wwwcsLrlnlLyedu/[oldham/1321/lecLures/lLeraLors/
O CMu unlv hLLp//wwwcscmuedu/afs/andrew/course/13/129/Cpp/10S1L/
O lnLro Lo S1L SCl hLLp//wwwsglcom/1echnology/S1L/sLl_lnLroducLlonhLml
O MumlLs S1L newble
gulde hLLp//wwwxrayllLhwlscedu/khan/sofLware/sLl/S1LnewblehLml Mu
mlL khans lnformaLlve S1L lnLroducLlon ls full of
examples hLLp//abelhlveno/C++/S1L/sLlnewhLml
O Cb[ecLSpace examples Cb[ecLSpace has conLrlbuLed over 300 examples Lo Lhe
publlc domaln and Lhese are a very good sLarL for
beglnnersfLp//buLlerhplhpcom/sLl/exampleszlp
O !oseph ? Laurlnos S1L
page hLLp//weberuwashlngLonedu/byLewave/byLewave_sLlhLml
O Mussers S1L docs and examples very
nlce hLLp//wwwcsrpledu/musser/sLlhLml
O S1L newble home
slLe hLLp//wwwxrayllLhwlscedu/khan/sofLware/sLl/S1LnewblehLml
O Marlan Corcorans S1L lAC fLp//buLlerhplhpcom/sLl/sLlfaq
STL Tutorial:
O 1he besL doc on LuLorlal
hLLp//wwwdecompllecom/hLml/LuLhLml Mlrror hLLp//mlpups
Llsefr/grundman/sLlLuLorlal/LuLorlalhLml
O very good hLLp//wwwyrlcouk/phll/sLl/sLlhLmlx
O C++ SLandard 1emplaLe LlbraryAnoLher greaL LuLorlal by Mark
Sebern hLLp//wwwmsoeedu/eecs/cese/resources/sLl/lndexhLm
O 8y !ak klrman hLLp//12918711236/Mlsc/CompuLer/sLl
LuLorlal/LuLorlal_9hLml Mlrrors
hLLp//wwwcsbrownedu/people/[ak/proglang/cpp/sLlLuL/LuLhLml hLLp//saL
urnmaLhuaaalaskaedu/af[h[/cs403/sLl/LuLorlalhLml
O 1echnlcal unlverslLy vlenna by !ohannes
Weldl hLLp//dnauglercssemoedu/LuLorlals/sLl mlrrorhLLp//wwwlnfosysLu
wlenacaL/8esearch/ComponenL/LuLorlal/prwmalnhLm
O Colorful 1uLorlal hLLp//wwwcodepro[ecLcom/cpp/sLllnLroducLlonasp
Ready-made Components Ior use with the STL
O S1L componenLs CollecLed by 8orls
lomlLche hLLp//wwwmeLabyLecom/fbp/sLl/componenLshLml
Main STL sites -
O C++ S1L from SCl hLLp//wwwsglcom/1echnology/S1L
O C++ S1L from 8l unlv hLLp//wwwcsrpledu/pro[ecLs/S1L/hLdocs/sLlhLml
O C++ S1L slLe Cu for S1L and Lhe mlrrorslLe
O S1L for C++
rogrammers hLLp//userwwweconhvunl/ammeraal/sLlcpphLml
O C++ S1L from halper hLLp//wwwhalpernwlghLsofLwarecom/sLdllb
scraLch/qulckrefhLml
23 Overview of the STL
The STL oIIers the programmer a number oI useIul data structures and algorithms. It
is made up the Iollowing components.
O ConLalners 1here are Lwo Lypes
o SequenLlal 1hls group comprlses Lhe vecLor llsL and dequeue Lypes
o SorLed AssoclaLlve 1hls group comprlses Lhe seL map mulLlseL and
mulLlmap Lypes
O lLeraLors 1hese are polnLer llke ob[ecLs LhaL allow Lhe user Lo sLep Lhrough Lhe
conLenLs of a conLalner
O Cenerlc AlgorlLhms 1he S1L provldes a wlde range of efflcenLly lmplemenLed
sLandard algorlLhms (for example flnd sorL and merge) LhaL work wlLh Lhe
conLalner Lypes (Some of Lhe conLalners have speclal purpose
lmplemenLaLlons of Lhese algorlLhms as member funcLlons)
O luncLlon Cb[ecLs A funcLlon ob[ecL ls an lnsLance of a class LhaL provldes a
deflnlLlon of operaLor() 1hls means LhaL you can use such an ob[ecL llke a
funcLlon
O AdapLors 1he S1L provldes
o ConLalner adapLors LhaL allow Lhe user Lo use say a vecLor as Lhe basls
of a sLack
o luncLlon adapLors LhaL allow Lhe user Lo consLrucL new funcLlon ob[ecLs
from exlsLlng funcLlon ob[ecLs
O AllocaLors Lvery S1L conLalner class uses an AllocaLor class Lo hold
lnformaLlon abouL Lhe memory model Lhe program ls uslng l shall LoLally
lgnore Lhls aspecL of Lhe S1L
I will be considering the use oI the vector, list, set and map containers. To make use oI
these containers you have to be able to use iterators so I shall have something to say
about STL iterators. Using the set and map containers can mean having to supply a
simple Iunction object to the instantiation so I shall also have something to say about
Iunction objects. I will only brieIly mention the algorithms supplied by the STL. I will
not mention adaptors at all.
I have taken liberties with some oI the types oI Iunction arguments -- Ior example
most oI the integer arguments reIerred to in what Iollows actually have type sizetype
which is typedeI'ed to an appropriate basic type depending on the allocation model
being used. II you want to see the true signatures oI the various Iunctions discussed
have a look at the Working Paper or the header Iiles.
There are a number oI utility classes supplied with the STL. The only one oI
importance to us is the pair class. This has the Iollowing deIinition:

template<class T1, class T2
class pair ,
public:
T1 first;
T2 second;
pair(const T1& a, const T2& b) : first(a), second(b) ,,

,;

and there is a convenient Iunction makepair with signature:

pair<T1,T2 make_pair(const T1& f, const T2&,s)

as well as implementations oI operator and operator . There is nothing
complicated about this template class and you should be able to use it without Iurther
guidance. To use it #include the header Iile pair.h. It crops up in a number oI places
but particularly when using the set and map classes.
232 Header Files
To use the various bits oI the STL you have to #include the appropriate header Iiles.
These may diIIer slightly Irom compiler to compiler but Ior g the ones oI interest
are:
O vectotb for Lhe vecLor Lype
O llstb for Lhe llsL Lype
O setb for Lhe seL Lype
O mopb for Lhe map Lype
O olqob for access Lo Lhe generlc algorlLhms
II you don't want to remember which is which you could just use stl.h which includes
all the above (and all the other header Iiles oI the STL as well).
233 The Container Classes Interface
The container classes have many member Iunctions that have the same names. These
Iunctions provide the same (or very similar) services Ior each oI the classes (though,
oI course, the implementations will be diIIerent). The Iollowing table lists the
Iunctions that we shall consider in more detail. A star opposite a Iunction name
indicates that the container type heading the column provides a member Iunction oI
that name.
Conta|ner C|ass Interface

CperaLlon
urpose vecLor LlsL SeL
Ma
p
comparlson * * * *
comparlson * * * *
begln lLeraLor * * * *

end lLeraLor * * * *

slze no of elemenLs * * * *

empLy ls conLalner empLy * * * *

fronL flrsL elemenL * *

back lasL elemenL * *

elemenL access/modlflcaLlon *

*

lnserL lnserL elemenL(s) * * * *

push_back lnserL new lasL elemenL * *


push_fronL lnserL new flrsL elemenL

*


erase remove elemenL(s) * * * *

pop_back remove lasL elemenL * *


pop_fronL remove lasL elemenL

*


II the Iollowing discussion leaves something unclear (and it will) you can always
write a small test program to investigate how some Iunction or Ieature behaves.
234 Vectors
A vector is an array like container that improves on the C array types. In particular
it is not neccessary to know how big you want the vector to be when you declare it,
you can add new elements to the end oI a vector using the pu8h_ba.k Iunction. (In
Iact the in8ert Iunction allows you insert new elements at any position oI the vector,
but this is a very ineIIicent operation -- iI you need to do this oIten consider using a
list instead).
onst^ucting Vecto^s
vector is a class template so that when declaring a vector object you have to state the
type oI the objects the vector is to contain. For example the Iollowing code Iragment

vector<int v1;
vector<string v2;
vector<FiniteAutomaton v3;

declares that v1 is a vector that holds integers, v2 a vector that holds strings and v3
holds objects oI type FiniteAutomaton (presumably an user deIined class type). These
declarations do not say anything about how large the vectors are to be
(implementations will use a deIault starting size) and you can grow them to as large as
you require.
ou can give an inital size to a vector by using a declaration like

vector<char v4(26);

which says that v4 is to be vector oI characters that initially has room Ior 26
characters. There is also a way to initailise a vector's elements. The declaration

vector<float v5(100,1.0);

says that v5 is a vector oI 100 Iloating point numbers each oI which has been
initialised to 1.0.
ecking p on You^ Vecto^
Once you have created a vector you can Iind out the current number oI elements it
contains by using the si:e Iunction. This Iunction takes no arguments and returns an
integer (strictly a value oI type si:etype, but this gets converted to an integer) which
says how many elements there are in the vector. What will be printed out by the
Iollowing small program?

<vector-size.cc=
#include <iostream.h
#include <vector.h

void main()
,
vector<int v1;
vector<int v2(10);
vector<int v3(10,7);

cout << "v1.size() returns " << v1.size() << endl;
cout << "v2.size() returns " << v2.size() << endl;
cout << "v3.size() returns " << v3.size() << endl;
,

To check on wether your vector is empty or not you can use the empty Iunction. This
takes no arguments and returns a boolean value, true iI the vector is empty, Ialse iI it
is not empty. What will be printed out by the Iollowing small program (true prints as 1
and Ialse prints as 0)?

<vector-empty.cc=
#include <iostream.h
#include <vector.h

void main()
,
vector<int v1;
vector<int v2(10);
vector<int v3(10,7);

cout << "v1.empty() has value " << v1.empty() << endl;
cout << "v2.empty() has value " << v2.empty() << endl;
cout << "v3.empty() has value " << v3.empty() << endl;
,

ccessing Elements of a Vecto^
ou can access a vector's elements using operator||. Thus, iI you wanted to print out
all the elements in a vector you could use code like

vector<int v;
// ...
for (int i=0; i<v.size(); i++)
cout << vi,;

(which is very similar to what you might write Ior a builtin array).
ou can also use operator|| to set the values oI the elements oI a vector.

vector<int v;
// ...
for (int i=0; i<v.size(); i++)
vi, = 2i;

The Iunction Iront gives access to the Iirst element oI the vector.

vector<char v(10,'a');
// ...
char ch = v.front();

ou can also change the Iirst element using Iront.

vector<char v(10,'a');
// ...
v.front() = 'b';

The Iunction back works the same as Iront but Ior the last element oI the vector.

vector<char v(10,'z');
// ...
char last = v.back();
v.back() = 'a';

Here is a simple example oI the use oI ||.

<vector-access.cc=
#include <vector.h
#include <iostream.h

void main()
,
vector<int v1(5);
int x;
cout << "Enter 5 integers (seperated by spaces):" << endl;
for (int i=0; i<5; i++)
cin v1i,;
cout << "You entered:" << endl;
for (int i=0; i<5; i++)
cout << v1i, << ' ';
cout << endl;
,

nse^ting and E^asing Vecto^ Elements
Along with operator|| as described above there are a number oI other ways to change
or access the elements in a vector.
O push_back wlll add a new elemenL Lo Lhe end of a vecLor
O pop_back wlll remove Lhe lasL elemenL of a vecLor
O lnserL wlll lnserL one or more new elemenLs aL a deslgnaLed poslLlon ln Lhe
vecLor
O erase wlll remove one or more elemenLs from a vecLor beLween deslgnaLed
poslLlons
Note that insert and erase are expensive operations on vectors. II you use them a lot
then you should consider using the list data structure Ior which they are more
eIIicient.

<vector-mod.cc=
#include <iostream.h
#include <vector.h

void main()
,
vector<int v;

for (int i=0; i<10; i++) v.push_back(i);
cout << "Vector initialised to:" << endl;
for (int i=0; i<10; i++) cout << vi, << ' ' ;
cout << endl;

for (int i=0; i<3; i++) v.pop_back();
cout << "Vector length now: " << v.size() << endl;
cout << "It contains:" << endl;
for (int i=0; i<v.size(); i++) cout << vi, << ' ';
cout << endl;

int a15,;
for (int i=0; i<5; i++) a1i, = 100;

v.insert(& v3,, & a10,,& a13,);
cout << "Vector now contains:" << endl;
for (int i=0; i<v.size(); i++) cout << vi, << ' ';
cout << endl;

v.erase(& v4,,& v7,);
cout << "Vector now contains:" << endl;
for (int i=0; i<v.size(); i++) cout << vi, << ' ';
cout << endl;
,

In the above a vector v has been declared then initialised using pushback. Then some
elements have been trimmed oII it's end using popback. Next an ordinary integer
array has been created and then some oI its elements inserted into v using insert.
Finally erase has been used to remove elements Irom v. The Iunctions used above take
arguments as Iollows.
O push_back Lakes a slngle argumenL of Lhe Lype of Lhe elemenLs held ln Lhe
vecLor
O pop_back Lakes no argumenLs lL ls a mlsLake Lo use pop_back on an empLy
vecLor
O lnserL has Lhree forms
o lnserL(pos 1 x) whlch wlll lnserL Lhe slngle elemenL x aL poslLlon pos ln
Lhe vecLor
o lnserL(pos sLarL end) whlch lnserLs a sequence of elemenLs from some
oLher conLalner aL poslLlon pos ln Lhe vecLor 1he
o sequence of elemenLs ls ldenLlfled as sLarLlng aL Lhe sLarL elemenL and
conLlnulng Lo buL noL lncludlng Lhe end elemenL
o lnserL(pos lnL rep 1 x) lnserLs rep coples of x aL poslLlon pos ln Lhe
vecLor
As lndlcaLed ln Lhe code above Lhe poslLlon pos should be Lhe address of Lhe elemenL
Lo lnserL aL whllsL Lhe sLarL and end argumenLs are llkewlse also addresses (1he Lrue
sLory ls LhaL Lhey are lLeraLors see nexL subsecLlon and followlng secLlon)
O erase has Lwo forms (pos sLarL and end have Lhe same Lypes as for Lhe lnserL
funcLlon)
o erase(pos) whlch wlll remove Lhe elemenL aL poslLlon pos ln Lhe vecLor
o lnserL(sLarLend) whlch wlll remove elemenLs sLarLlng aL posLlon sLarL
upLo buL noL lncludlng Lhe elemenL aL poslLlon end
Vecto^ te^ato^s
The simple way to step through the elements oI a vector v is as we have done above:

for (int i=0; i<v.size(); i++) , ... vi, ... ,

Another way is to use iterators. An iterator can be thought oI as a pointer into the
container, incrementing the iterator allows you to step through the container. For
container types other than vectors iterators are the only way to step through the
container.
For a vector containing elements oI type T:

vector<T v;

an iterator is declared as Iollows:

vector<T::iterator i;

Such iterators are constructed and returned by the Iunctions begin() and end(). ou
can compare two iterators (oI the same type) using and !, increment using and
dereIerence using *. |In Iact vector iterators allow more operations on them - see next
section Ior more inIormation|.
Here is an illustration oI how to use iterators with vectors.

<vector-iterator.cc=
#include <iostream.h
#include <vector.h

void main()
,
vector<int v(10);
first is ``less'' than the second

int j = 1;

vector<int::iterator i;

// Fill the vector v with integers 1 to 10.
i = v.begin();
while (i != v.end())
,
i = j;
j++;
i++;
,

// Square each element of v.
for (i=v.begin(); i!=v.end(); i++) i = (i) (i);

// Print out the vector v.
cout << "The vector v contains: ";
for (i=v.begin(); i!=v.end(); i++) cout << i << ' ';
cout << endl;

,

Note how *i can be used on the leIt-hand side oI an assignment statement so as to
update the element pointed at by i, and on the right-hand side to access the current
value.
ompa^ing Vecto^s
ou can compare two vectors using and . will return true only iI both vectors
have the same number oI elements and all elements are equal. The Iunctions
perIorms a lexicographic comparison oI the two vectors. This works by comparing the
vectors element by element. Suppose we are comparing v1 and v2 (that is v1 v2?).
Set i0. II v1|i| v2|i| then return true, iI v1|i| ~ v2|i| then return Ialse, otherwise
increment i (that is move on to the next element). II the end oI v1 is reached beIore v2
return true, otherwise return Ialse. Lexicographic order is also known as dictionary
order. Some examples:

(1,2,3,4) < (5,6,7,8,9,10) is false.
(1,2,3) < (1,2,3,4) is true
(1,2,3,4) < (1,2,3) is false
(0,1,2,3) < (1,2,3) is true

The Iollowing code illustrates the third example above.

<vector-comp.cc=
#include <vector.h
#include <iostream.h

void main()
,
vector<int v1;
vector<int v2;
for (int i=0; i<4; i++) v1.push_back(i+1);
for (int i=0; i<3; i++) v2.push_back(i+1);

cout << "v1: ";
for (int i=0; i<v1.size(); i++) cout << v1i, << ' ';
cout << endl;

cout << "v2: ";
for (int i=0; i<v2.size(); i++) cout << v2i, << ' ';
cout << endl;

cout << "v1 < v2 is: " << (v1<v2 . "true" : "false") << endl;
,

1he comparlson operaLors and also work
235 Iterators and the STL
See the section STL ReIerences
236 Lists
See the section STL ReIerences
237 Sets
The set container type allows an user to store and retrieve elements directly rather
than through an index into the container. The set container acts as a mathematical set
in that it holds only distinct elements. However unlike a mathematical set, elements in
a set container are held in (an user-supplied) order. In practise this is only a minor
restriction on treating a set container as an implementation oI the mathematical set
abstract data type, and it allows Ior a much more eIIicent implementation than an
unordered approach.
onst^ucting Sets
Two template arguments are required to construct a set container -- the type oI the
objects the set is to contain and a Iunction object that can compare two elements oI the
given type, that is:

set<T, Compare s;

(The declaration set T ~ s should also be possible -- it would use a deIault template
argument less T ~ as the second argument, but many C compilers (including
g) cannot as yet cope with deIault template arguments.)
For simple types T we can use the Iunction object less T ~ ( without having to
worry about what a ``Iunction object'' is), Ior example all the Iollowing are legal set
declarations.

set<int, less<int s1;
set<double, less<double s2;
set<char, less<char s3;
set<string, less<string s4;

(Note that the space between the two Iinal ~'s in the template is required - otherwise
the compiler will interpret ~~ as the right shiIt operator.) In each oI these cases the
Iunction object makes use oI the operator as deIined Ior the the underlying type
(that is int, double, char and string).
The Iollowing code declares a set oI integers, then adds some integers to the set using
the insert method and then prints out the set members by iterating through the set.
ou will note that the set's contents are printed out in ascending order even though
they were added in no particular order.

<set-construct1.cc=
#include <iostream.h
#include <set.h

void main()
,
set<int, less<int s;
set<int, less<int ::iterator i;

s.insert(4);
s.insert(0);
s.insert(-9);
s.insert(7);
s.insert(-2);
s.insert(4);
s.insert(2);

cout << The set contains the elements: ;
for (i=s.begin(); i!=s.end(); i++) cout << i << ' ';
cout << endl;
,

Note that 4 is added twice but only turns up once on the list oI elements -- which is
what one expects oI a set.
at a^e Function Ub|ects?
One oI the niIty Ieatures oI C is the ability to overload operators, so that one can
have mean whatever one likes Ior your newly designed class. One oI the operators
C allows you to overload is the Iunction call operator () and this allows you to
create classes whose instances can behave like Iunctions in many ways. These are
Iunction objects.
Here is a simple example.

<function-object.cc=
#include <iostream.h

template<class T
class square ,
public:
T operator()(T x) , return xx; ,
,;
// This can be used with any T for which is defined.

void main()
,
// Create some function objects.
square<double f1;
square<int f2;

// Use them.
cout << 5.1^2 = << f1(5.1) << endl;
cout << 100^2 = << f2(100) << endl;

// The following would result in a compile time error.
// cout << 100.1^2 = << f2(100.1) << endl;

,

Function objects are used in a number oI places in the STL. In particular they are used
when declaring sets and maps.
The Iunction object required Ior these purposes, let's suppose it is called comp, must
satisIy the Iollowing requirements.
1 lf comp(xy) and comp(yz) are Lrue for ob[ecLs x y and z Lhen comp(xz) ls also
Lrue
2 comp(xx) ls false for every ob[ecL x
II Ior any particular objects x and y, both comp(x,y) and comp(y,x) are Ialse then x
and y are deemed to be equal.
This, in Iact, is just the behaviour oI the strictly-less-than relation (ie ) on numbers.
The Iunction object less T ~ used above is deIined in terms oI a operator Ior the
type T. It's deIinition can be thought oI as Iollows.

template<class T
struct less ,
bool operator()(T x, T y) , return x<y; ,
,

(The actual deIinition uses reIerences, has appropriate const annotations and inherits
Irom a template class binaryIunction.)
This means that iI the type T has operator deIined Ior it then you can use less T ~
as the comparator when declaring sets oI T. ou might still want to use a special
purpose comparator iI the supplied operator is not appropriate Ior your purposes.
Here is another example. This deIines a simple class with a deIinition oI operator
and a Iunction object that perIorms a diIIerent comparison. Note that the overloaded
and () operators should be given const annotations so that the Iunctions work correctly
with the STL.

<set-construct2.cc=
#include <iostream.h
#include <set.h

// This class has two data members. The overloaded operator< compares
// such classes on the basis of the member f1.
class myClass ,
private:
int f1;
char f2;
public:
myClass(int a, char b) : f1(a), f2(b) ,,
int field1() const , return f1; ,
char field2() const , return f2; ,
bool operator<(myClass y) const
, return (f1<y.field1()); ,
,;

// This function object compares objects of type myClass on the basis
// of the data member f2.
class comp_myClass ,
public:
bool operator()(myClass c1, myClass c2) const
, return (c1.field2() < c2.field2()); ,
,;

void main()
,
set<myClass, less<myClass s1;
set<myClass, less<myClass ::iterator i;
set<myClass, comp_myClass s2;
set<myClass, comp_myClass::iterator j;

s1.insert(myClass(1,'a'));
s2.insert(myClass(1,'a'));
s1.insert(myClass(1,'b'));
s2.insert(myClass(1,'b'));
s1.insert(myClass(2,'a'));
s2.insert(myClass(2,'a'));

cout << Set s1 contains: ;
for (i=s1.begin(); i!=s1.end(); i++)
, cout << ( << (i).field1() << ,
<< (i).field2() << ) << ' ';
,
cout << endl;

cout << Set s2 contains: ;
for (j=s2.begin(); j!=s2.end(); j++)
, cout << ( << (j).field1() << ,
<< (j).field2() << ) << ' ';
,
cout << endl;

,

The set s1 contains (1,a) and (2,a) as comparison is on the data member I1, so that
(1,a) and (1,b) are deemed the same element. The set s2 contains (1,a) and (1,b) as
comparison is on the data member I2, so that (1,a) and (2,a) are deemed the same
element.
^inting tility
The way we have printed out the sets in the previous examples is a little awkward so
the Iollowing header Iile containing a simple overloaded version oIoperator has
been written. It works Iine Ior small sets with simple element types.

<printset.h=
#ifndef _PRINTSET_H
#define _PRINTSET_H

#include <iostream.h
#include <set.h

template<class T, class Comp
ostream& operator<<(ostream& os, const set<T,Comp& s)
,
set<T,Comp::iterator iter = s.begin();
int sz = s.size();
int cnt = 0;

os << ,;
while (cnt < sz-1)
,
os << iter << ,;
iter++;
cnt++;
,
if (sz != 0) os << iter;
os << ,;

return os;
,
#endif

The use here oI as an output routine Ior a set assumes that has been deIined Ior
the set elements, and uses this to print a comma delimited list oI the set elements
wrapped in curly braces. It will be used without comment in the Iollowing examples.
ow Many Elements?
ou can determine iI a set is empty or not by using the empty() method. ou can Iind
out how many elements there are in a set by using the size() method. These methods
take no arguments, empty() returns true or Ialse and size() returns an integer.

<set-size.cc=
#include <iostream.h
#include <set.h
#include printset.h

void main()
,
set<int, less<int s;

cout << The set s is
<< (s.empty() . empty. : non-empty.) << endl;
cout << It has << s.size() << elements. << endl;

cout << Now adding some elements... << endl;

s.insert(1);
s.insert(6);
s.insert(7);
s.insert(-7);
s.insert(5);
s.insert(2);
s.insert(1);
s.insert(6);

cout << The set s is now
<< (s.empty() . empty. : non-empty.) << endl;
cout << It has << s.size() << elements. << endl;
cout << s = << s << endl;
,

ecking te Equality of Sets.
Two sets may be checked Ior equality by using . This equality test works by testing
in order the corresponding elements oI each set Ior equality using T::operator.

<set-equality.cc=
#include <iostream.h
#include <set.h
#include printset.h

void main()
,
set<int, less<int s1, s2 ,s3;

for (int i=0; i<10; i++)
,
s1.insert(i);
s2.insert(2i);
s3.insert(i);
,

cout << s1 = << s1 << endl;
cout << s2 = << s2 << endl;
cout << s3 = << s3 << endl;
cout << s1==s2 is: << (s1==s2 . true. : false.) << endl;
cout << s1==s3 is: << (s1==s3 . true. : false.) << endl;
,

It is also possible to compare two sets using . The comparison s1 s2 is true iI the
set s1 is lexicographically less than the set s2, otherwise it is Ialse.
dding and Deleting Elements
The way to add elements to a set is to use the insert method (as we have done above).
The way to delete elements Irom a set is to use the erase method.
For a set holding elements oI type T these methods come in Iollowing Iorms:
O pa|r |terator boo| |nsert(1 x) 1hls ls Lhe sLandard lnserL funcLlon 1he
reLurn value may be lgnored or used Lo LesL lf Lhe lnserLlon succeeded (LhaL ls
Lhe elemenL was noL already ln Lhe seL) lf Lhe lnserLlon succeeded Lhe
boolean componenL wlll be Lrue and Lhe lLeraLor wlll polnL aL Lhe [usL lnserLed
elemenL lf Lhe elemenL ls already presenL Lhe boolean componenL wlll be
false and Lhe lLeraLor wlll polnL aL Lhe elemenL x already presenL
O |terator |nsert(|terator pos|t|on 1 x) 1hls verslon of Lhe lnserL funcLlon
Lakes ln addlLlon Lo Lhe elemenL Lo lnserL an lLeraLor sLaLlng where Lhe lnserL
funcLlon should begln Lo search 1he reLurned lLeraLor polnLs aL Lhe newly
lnserLed elemenL (or Lhe already presenL elemenL)
O |nt erase(1 x) 1hls verslon of Lhe erase meLhod Lakes an elemenL Lo deleLe
and reLurns 1 lf Lhe elemenL was presenL (and removes lL) or 0 lf Lhe elemenL
was noL presenL
O vo|d erase(|terator pos|t|on) 1hls verslon Lakes an lLeraLor polnLlng aL some
elemenL ln Lhe seL and removes LhaL elemenL
O vo|d erase(|terator f|rst |terator |ast) 1hls verlon Lakes Lwo lLeraLors polnLlng
lnLo Lhe seL and removes all Lhe elemenLs ln Lhe range flrsLlasL
The Iollowing example illustrates these various Iorms.

<set-add-delete.cc=
#include <iostream.h
#include <set.h
#include printset.h

void main()
,
set<int, less<int s1;

// Insert elements in the standard fashion.
s1.insert(1);
s1.insert(2);
s1.insert(-2);

// Insert elements at particular positions.
s1.insert(s1.end(), 3);
s1.insert(s1.begin(), -3);
s1.insert((s1.begin()++)++, 0);

cout << s1 = << s1 << endl;

// Check to see if an insertion has been successful.
pair<set<int, less<int ::iterator,bool x = s1.insert(4);
cout << Insertion of 4 << (x.second . worked. : failed.)
<< endl;
x = s1.insert(0);
cout << Insertion of 0 << (x.second . worked. : failed.)
<< endl;

// The iterator returned by insert can be used as the position
// component of the second form of insert.
cout << Inserting 10, 8 and 7. << endl;
s1.insert(10);
x=s1.insert(7);
s1.insert(x.first, 8);

cout << s1 = << s1 << endl;

// Attempt to remove some elements.
cout << Removal of 0 << (s1.erase(0) . worked. : failed.)
<< endl;
cout << Removal of 5 << (s1.erase(5) . worked. : failed.)
<< endl;

// Locate an element, then remove it. (See below for find.)
cout << Searching for 7. << endl;
set<int,less<int ::iterator e = s1.find(7);
cout << Removing 7. << endl;
s1.erase(e);

cout << s1 = << s1 << endl;

// Finally erase everything from the set.
cout << Removing all elements from s1. << endl;
s1.erase(s1.begin(), s1.end());
cout << s1 = << s1 << endl;
cout << s1 is now << (s1.empty() . empty. : non-empty.)
<< endl;
,

Finding Elements
We mention two member Iunctions that can be used to test iI an element is present in
a set or not.
O |terator f|nd(1 x) 1hls searches for Lhe elemenL x ln Lhe seL lf x ls found lL
reLurns an lLeraLor polnLlng aL x oLherwlse lL reLurns end()
O |nt count(1 x) 1hls reLurns 1 lf lL flnds x ln Lhe seL and 0 oLherwlse (1he
counL funcLlon for mulLlseLs reLurns Lhe number of coples of Lhe elemenL ln
Lhe seL whlch may be more Lhan 1 Pence l guess Lhe name of Lhe funcLlon)
The use oI Iind has been illustrated above. We could use count to write a simple
template based set membership Iunction. (This should also provide a version that
takes a reIerence to the argument x.)

<setmember.h=
#ifndef _SETMEMBER_H
#define _SETMEMBER_H
#include <set.h

template<class T, class Comp
bool member(T x, set<T,Comp& s)
,
return (s.count(x)==1 . true : false);
,
#endif

Which might be used as follows.

<set-membership.cc=
#include <iostream.h
#include <set.h
#include printset.h
#include setmember.h

void main()
,
set<int, less<int s;
for (int i= 0; i<10; i++) s.insert(i);
cout << s = << s << endl;
cout << 1 is << (member(1,s) . : not) << a member of s
<< endl;
cout << 10 is << (member(10,s) . : not) << a member of s
<< endl;
,

Set Teo^etic Upe^ations
The STL supplies as generic algorithms the set operations includes, union,
intersection, diIIerence and symmetric diIIIerence. To gain access to these Iunctions
you need to include algo.h. (In what Iollows iter stands Ior an appropriate iterator).
O bool lncludes(lLer f1lLer l1lLer f2lLer l2)
This checks to see iI the set represented by the range |I2,l2| is included in the
set |I1,l1|. It returns true iI it is and Ialse otherwise. So to check to see iI one
set is included in another you would use
includes(s1.begin(), s1.end(), s2.begin(), s2.end())
The includes Iunction checks the truth oI 3#3 ( that is oI 4#4). This Iunction
assumes that the sets are ordered using the comparison operator . II some
other comparison operator has been used this needs to be passed to includes as
an extra (Iunction object) argument aIter the other arguments.
O lLer seL_unlon(lLer f1lLer l1lLer f2lLer l2lLer resulL)
This Iorms the union oI the sets represented by the ranges |I1,l1| and |I2,l2|.
The argument result is an output iterator that points at the start oI the set that is
going to hold the union. The return value oI the Iunction is an output iterator
that points at the end oI the new set.
The Iact that the result argument is an output iterator means that you cannot use
setunion in the Iollowing, natural, Iashion:

set<int, less<int s1, s2, s3;
// Add some elements to s1 and s2 ...
// Then form their union. (This does not work!)
set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
s3.begin());

The reason is that begin() (also end()) when used with sets (or maps) returns a
(constant) input iterator. This type oI iterator allows you to access elements oI the set
Ior reading but not writing. (And this is a Good Thing since iI you could assign to a
dereIerenced iterator (as in (*i) ...) then you could destroy the underlying order oI
the set.)
The solution is to use an insert iterator based on the set type. This, basically, converts
an assignment (*i)value (which is illegal) into a (legal) insertion s.insert(i,value)
(where s is the set object that the iterator i is pointing into). It is used as Iollows:

// Typedef for convenience.
typedef set<int, less<int intSet;
intSet s1, s2, s3;
// Add some elements to s1 and s2 ...
// Then form their union.
set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
insert_iterator<intSet(s3,s3.begin()) );

Here is an example illustrating all these operations.

<set-theory.cc=
#include <iostream.h
#include <set.h
#include <algo.h
#include <iterator.h
#include printset.h

void main()
,
typedef set<int, less<int intSet;

intSet s1, s2, s3, s4;

for (int i=0; i<10; i++)
, s1.insert(i);
s2.insert(i+4);
,
for (int i=0; i<5; i++) s3.insert(i);

cout << s1 = << s1 << endl;
cout << s2 = << s2 << endl;
cout << s3 = << s3 << endl;

// Is s1 a subset of s2.
bool test = includes(s2.begin(),s2.end(),s1.begin(),s1.end());
cout << s1 subset of s2 is << (test . true. : false.) << endl;

// Is s3 a subset of s1.
test = includes(s1.begin(),s1.end(),s3.begin(),s3.end());
cout << s3 subset of s1 is << (test . true. : false.) << endl;

// Form the union of s1 and s2.
set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet(s4,s4.begin()) );
cout << s1 union s2 = << s4 << endl;

// Erase s4 and form intersection of s1 and s2. (If we don't erase
// s4 then we will get the previous contents of s4 as well).
s4.erase(s4.begin(),s4.end());
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet(s4,s4.begin()) );
cout << s1 intersection s2 = << s4 << endl;

// Now set difference.
s4.erase(s4.begin(),s4.end());
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet(s4,s4.begin()) );
cout << s1 minus s2 = << s4 << endl;

// Set difference is not symmetric.
s4.erase(s4.begin(),s4.end());
set_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet(s4,s4.begin()) );
cout << s2 minus s1 = << s4 << endl;

// Finally symmetric difference.
s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet(s4,s4.begin()) );
cout << s1 symmetric_difference s2 = << s4 << endl;

// Which is symmetric!
s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet(s4,s4.begin()) );
cout << s2 symmetric_difference s1 = << s4 << endl;
,

238 Maps
See the section STL ReIerences
239 STL Algorithms
See the section STL ReIerences
24 Threads in C++
O l8M pLhread user Culde 1hread concepLs Al
reference hLLp//wwwas400lbmcom/developer/Lhreads/ugulde/documenLh
Lm and mlrror slLe ls aL l8M maln slLe
O Cp1hread Llbrary for C++ provldes ob[ecL orlenLed framework ln C++ for
Lhreads and unlx slgnals on Lop of sysLem level Lhreads (currenLly CSlx
1hreads) hLLp//llnfsldcvuLcz/kra/lndexhLml
O 1hread!ack supporLs !avallke mulLlLhread programmlng model wlLh plaLform
lndependenL C++ class llbrary hLLp//wwwesmco[p/dlvlslons/open
sys/1hread!ack/lndexehLml and here ls Lhe downloadslLe
O AL ls Lhe AL orLable LnvlronmenL and class llbrarles for wrlLlng porLable
Lhreaded servers ln C++ under unlx (pLhread) and Wln32 Als AL provldes
porLable class absLracLlon for Lhreads sockeLs flle handllng and
synchronlzaLlon ob[ecLs 1he goal of AL ls Lo make wrlLlng Lhreaded servers ln
C++ boLh pracLlcal and convlenL even for small and slmple pro[ecLs and hence
slmpllclLy and low runLlme overhead are deslgn
goalshLLp//wwwvoxlllaorg/pro[ecLs/pro[apehLml
O orLabale 1hread Llb hLLp//wwwmedlaosakacuac[p/kabe/1L
O 1hread8ecyllng ln C++ hLLp//wwwslgsde/hLml/kuhlmannhLml
24 Threads Tutorial
O ?ou can download all Lhe LuLorlals ln one flle from aldevslLe
O 1hreads LuLorlal ls
aL hLLp//wwwmaLharlzonaedu/swlg/pLhreads/LhreadshLml
O PL81 LuLorlal aL hLLp//wwwherLorg/docs/LuLorlals go here Lo search for
1hreads
O lnLro Lo Lhreads aL llnux[ournal
O norLh Arlzona unlv nAu
O oslx Lhreads AccLcom mulLlLhread
242 Designing a Thread Class in C++
This section is written by Ryan Teixeira and the document is located here .
nt^oduction
Multi threaded programming is becomming ever more popular. This section presents a
design Ior a C class that will encapsulate the threading mechanism. Certain aspects
oI thread programming, like mutexes and semaphores are not discussed here. Also,
operating system calls to manipulate threads are shown in a generic Iorm.
B^ief nt^oduction To T^eads
To understand threads one must think oI several programs running at once. Imagine
Iurther that all these programs have access to the same set oI global variables and
Iunction calls. Each oI these programs would represent a thread oI execution and is
thus called a thread. The important diIIerentiation is that each thread does not have to
wait Ior any other thread to proceed. All the threads proceed simultaneously. To use a
metaphor, they are like runners in a race, no runner waits Ior another runner. They all
proceed at their own rate.
Why use threads you might ask. Well threads can oIten improve the perIormance oI
an application and they do not incur signiIicant overhead to implement. They
eIIectively give good bang Ior a buck. Imagine an image server program that must
service requests Ior images. The program gets a request Ior an image Irom another
program. It must then retieve the image Irom a database and send it to the program
that requested it. II the server were implemented in a single threaded approach, only
one program could request at a time. When it was busy retrieving an image and
sending it to a requestor, it could not service other requests. OI course one could still
implement such a system without using threads. It would be a challenge though.
Using threads, one can very naturally design a system to handle multiple requests. A
simple approach would be to create a thread Ior each request received. The main
thread would create this thread upon receipt oI a request. The thread would then be
responsible Ior the conversation with the client program Irom that point on. AIter
retrieving the image, the thread would terminate itselI. This would provide a smooth
system that would continue to service requests even though it was busy serviceing
other requests at the same time.
Basic pp^oac
The create a thread, you must speciIy a Iunction that will become the entry point Ior
the thread. At the operating system level, this is a normal Iunction. We have to do a
Iew tricks to wrap a C class around it because the entry Iunction cannot be a
normal member Iunction oI a class. However, it can be a static member Iunction oI a
class. This is what we will use as the entry point. There is a gotcha here though. Static
member Iunctions do not have access to the this pointer oI a C object. They can
only access static data. Fortunately, there is way to do it. Thread entry point Iunctions
take a void * as a parameter so that the caller can typecast any data and pass in to the
thread. We will use this to pass this to the static Iunction. The static Iunction will then
typecast the void * and use it to call a non static member Iunction.
Te mplementation
It should be mentioned that we are going to discuss a thread class with limited
Iunctionality. It is possible to do more with threads than this class will allow.

class Thread
,
public:
Thread();
int Start(void arg);
protected:
int Run(void arg);
static void EntryPoint(void);
virtual void Setup();
virtual void Execute(void);
void Arg() const ,return Arg_;,
void Arg(void a),Arg_ = a;,
private:
THREADID ThreadId_;
void Arg_;

,;

Thread::Thread() ,,

int Thread::Start(void arg)
,
Arg(arg); // store user data
int code = thread_create(Thread::EntryPoint, this, & ThreadId_);
return code;
,

int Thread::Run(void arg)
,
Setup();
Execute( arg );
,

/static /
void Thread::EntryPoint(void pthis)
,
Thread pt = (Thread)pthis;
pthis-Run( Arg() );
,

virtual void Thread::Setup()
,
// Do any setup here
,

virtual void Thread::Execute(void arg)
,
// Your code goes here
,

It is important to understand that we are wrapping a C object around a thread. Each
object will provide an interIace to a single thread. The thread and the object are not
the same. The object can exist without a thread. In this implementation, the thread
does not actually exist until the Start Iunction is called.
Notice that we store the user argument in the class. This is necessary because we need
a place to store it temporarily until the thread is started. The operating system thread
call allows us to pass an argument but we have used it to pass the this pointer. So we
store the real user argument in the class itselI and when the execute Iunction is called
it can get access to the argument.
Thread(); This is the constructor.
int Start(void ` arg); This Iunction provides the means to create the thread and start
it going. The argument arg provides a way Ior user data to be passed into the thread.
Start() creates the thread by calling the operating system thread creation Iunction.
int Run(void ` arg); This is a protected Iunction that should never be tampered with.
static void ` EntryPoint(void ` pthis); This Iunction serves as the entry point to the
thread. It simply casts pthis to Thread * and
virtual void Setup(); This Iunction is called aIter the thread has been created but
beIore Execute() is called. II you override this Iunction, remember to call the parent
class Execute().
virtual void Execute(void `); ou must override this Iunction to provide your own
Iunctionality.
sing Te T^ead lass
To use the thread class, you derive a new class. you override the Execute() Iunction
where you provide your own Iunctionality. ou may override the Setup() Iunction to
do any start up duties beIore Execute is called. II you override Setup(), remember to
call the parent class Setup().
onclusion
This section presented an implementation oI a thread class written in C. OI course
it is a simple approach but it provides a sound Ioundation upon which to build a more
robust design.
II you have comments or suggestions, email to Ryan Teixeira
25 C++ Utilities
Visit the Iollowing sites Ior C Utilities
O C++ 8lnary llle
l/C hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/cpp_8lnarylllelChL
ml and aL mlrror slLe
O orLablllLy
Culde hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/cpp_orLablllLyC
uldehLml and aL mlrror slLe
O SnlppeLs collecLlons of C++
rouLlnes hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/cpp_SnlppeLs
hLml and aL mlrror slLe and aL snlppeLs slLe
O escape lS8 for C++ rovldes lnformaLlon on how Lo develop and program
dlsLrlbuLed ob[ecLbased appllcaLlons ln C++ for Wlndows and unlx uslng Lhe
neLscape lnLerneL Servlce
8roker hLLp//docslplaneLcom/docs/manuals/enLerprlse/cpluspg/conLenLshL
m
O Common c++ hLLp//wwwvoxlllaorg/pro[ecLs/pro[apehLml
O Large LlsL of free C++
llbs hLLp//wwwLhefreecounLrycom/developerclLy/freellbhLml
O C++ 1ools hLLp//developmenLfreeserverscom
O C++ 1ools Cu! hLLp//wwwcu[com/code
O C++llbs unlv of vaasa hLLp//garbouwasafl/pc/clanghLml
26 Other Formats of this Document
This document is published in 14 diIIerent Iormats namely - DVI, Postscript, Latex,
Adobe Acrobat PDF, LyX, GNU-inIo, HTML, RTF(Rich Text Format), Plain-text,
Unix man pages, single HTML Iile, SGML (Linuxdoc Iormat), SGML (Docbook
Iormat), MS WinHelp Iormat.
This howto document is located at -
O hLLp//wwwllnuxdocorg and cllck on PCW1Cs and search for howLo
documenL name uslng C18L+f or AL1+f wlLhln Lhe webbrowser
ou can also Iind this document at the Iollowing mirrors sites -
O hLLp//wwwcalderacom/Lu/PCW1C
O hLLp//wwwllnuxuclaedu/Lu
O hLLp//wwwccgaLechedu/llnux/Lu
O hLLp//wwwredhaLcom/mlrrors/Lu
O CLher mlrror slLes near you (neLworkaddresswlse) can be found
aL hLLp//wwwllnuxdocorg/mlrrorshLml selecL a slLe and go Lo dlrecLory
/Lu/PCW1C/xxxxxPCW1ChLml
O ?ou can geL Lhls PCW1C documenL as a slngle flle Lar ball ln P1ML uvl
osLscrlpL or SCML formaLs from
fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C/oLher
formaLs/ and hLLp//wwwllnuxdocorg/docshLml#howLo
O laln LexL formaL ls
ln fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C and hLLp//wwwllnuxdoc
org/docshLml#howLo
O Slngle P1ML flle formaL ls ln hLLp//wwwllnuxdocorg/docshLml#howLo
Single HTML Iile can be created with command (see man sgml2html) -
sgml2html -split 0 xxxxhowto.sgml
O 1ranslaLlons Lo oLher languages llke lrench Cerman Spanlsh Chlnese
!apanese are
ln fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C andhLLp//wwwllnuxdoc
org/docshLml#howLo Any help from you Lo LranslaLe Lo oLher languages ls
welcome
1he documenL ls wrlLLen uslng a Lool called SCML1ools whlch can be goL from
hLLp//wwwsgmlLoolsorg Complllng Lhe source you wlll geL Lhe followlng
commands llke
O sgml2hLml xxxxhowLosgml (Lo generaLe hLml flle)
O sgml2hLml spllL 0 xxxxhowLosgml (Lo generaLe a slngle page hLml flle)
O sgml2rLf xxxxhowLosgml (Lo generaLe 81l flle)
O sgml2laLex xxxxhowLosgml (Lo generaLe laLex flle)
26 Acrobat PDF format
PDF Iile can be generated Irom postscript Iile using either
acrobat distill or Ghostscript. And postscript Iile is generated Irom DVI which in
turn is generated Irom LaTex Iile. ou can download distill soItware
Irom http://www.adobe.com. Given below is a sample session:

bash$ man sgml2latex
bash$ sgml2latex filename.sgml
bash$ man dvips
bash$ dvips -o filename.ps filename.dvi
bash$ distill filename.ps
bash$ man ghostscript
bash$ man ps2pdf
bash$ ps2pdf input.ps output.pdf
bash$ acroread output.pdf &

Cr you can use ChosLscrlpL command ps2pdf ps2pdf ls a workallke for nearly all Lhe
funcLlonallLy of Adobes AcrobaL ulsLlller producL lL converLs osLScrlpL flles Lo
orLable uocumenL lormaL (ul) flles ps2pdf ls lmplemenLed as a very small
command scrlpL (baLch flle) LhaL lnvokes ChosLscrlpL selecLlng a speclal ouLpuL
devlce called pdfwr|te ln order Lo use ps2pdf Lhe pdfwrlLe devlce musL be lncluded
ln Lhe makeflle when ChosLscrlpL was complled see Lhe documenLaLlon on bulldlng
ChosLscrlpL for deLalls
262 Convert Linuxdoc to Docbook format
This document is written in linuxdoc SGML Iormat. The Docbook SGML Iormat
supercedes the linuxdoc Iormat and has lot more Ieatures than linuxdoc. The linuxdoc
is very simple and is easy to use. To convert linuxdoc SGML Iile to Docbook SGML
use the program ld2dbsh and some perl scripts. The ld2db output is not 100 clean
and you need to use the clean_ld2dbpl perl script. ou may need to manually correct
Iew lines in the document.
O uownload ld2db program
from hLLp//wwwdcsglaacuk/rrL/docbookhLml or from Al uev slLe
O uownload Lhe cleanup_ld2dbpl perl scrlpL from from Al uev slLe
1he ld2dbsh ls noL 100 clean you wlll geL loLs of errors when you run

bash$ ld2db.sh file-linuxdoc.sgml db.sgml
bash$ cleanup.pl db.sgml db_clean.sgml
bash$ gvim db_clean.sgml
bash$ docbook2html db.sgml

And you may have Lo manually edlL some of Lhe mlnor errors afLer runnlng Lhe perl
scrlpL lor eg you may need Lo puL closlng Lag /ara for each LlsLlLem
263 Convert to MS WinHelp format
ou can convert the SGML howto document to MicrosoIt Windows Help Iile, Iirst
convert the sgml to html using:

bash$ sgml2html xxxxhowto.sgml (to generate html file)
bash$ sgml2html -split 0 xxxxhowto.sgml (to generate a single page
html file)

1hen use Lhe Lool PLml1oPlp ?ou can also use sgml2rLf and Lhen use Lhe 81l flles for
generaLlng wlnhelp flles
264 Reading various formats
In order to view the document in dvi Iormat, use the xdvi program. The xdvi program
is located in tetex-xdvi*.rpm package in Redhat Linux which can be located through
ControlPanel , Applications , Publishing , TeX menu buttons. To read dvi document
give the command -
xdvi -geometry 80x90 howto.dvi
man xdvi
And reslze Lhe wlndow wlLh mouse 1o navlgaLe use Arrow keys age up age
uown keys also you can use f d u c l r p n leLLer keys Lo move up down
cenLer nexL page prevlous page eLc 1o Lurn off experL menu press x
ou can read postscript Iile using the program 'gv' (ghostview) or 'ghostscript'. The
ghostscript program is in ghostscript*.rpm package and gv program is in gv*.rpm
package in Redhat Linux which can be located through ControlPanel , Applications ,
Graphics menu buttons. The gv program is much more user Iriendly than ghostscript.
Also ghostscript and gv are available on other platIorms like OS/2, Windows 95 and
NT, you view this document even on those platIorms.
O CeL ghosLscrlpL for Wlndows 93 CS/2 and for all CSes
from hLLp//wwwcswlscedu/ghosL
To read postscript document give the command -
gv howto.ps
ghostscript howto.ps
ou can read HTML Iormat document using Netscape Navigator, MicrosoIt Internet
explorer, Redhat Baron Web browser or any oI the 10 other web browsers.
ou can read the latex, LyX output using LyX a X-Windows Iront end to latex.
27 Translations To Other Languages
O 1ranslaLlon Lo ollsh ls
aL hLLp//sLronywppl/wp/chq/c/howLo/node1hLml Lhanks Lo uarek
CsLolskl uarek CsLolskl
O 1ranslaLlons Lo oLher languages llke lrench Cerman Spanlsh Chlnese
!apanese are
ln fLp//wwwllnuxdocorg/pub/Llnux/docs/PCW1C andhLLp//wwwllnuxdoc
org/docshLml#howLo
Any help from you Lo LranslaLe Lo oLher languages ls welcome

28 Copyright
Copyright policy is GNU/GPL as per LDP (Linux Documentation project). LDP is a
GNU/GPL project. Additional requests are that you retain the author's name, email
address and this copyright notice on all the copies. II you make any changes or
additions to this document then you please intimate all the authors oI this document.
Brand names mentioned in this document are property oI their respective owners.

29 Appendix A String Program Files
ou can download all programs as a single targz Iile Irom Download String and
give the Iollowing command to unpack

bash$ man tar
bash$ tar ztvf C++Programming-HJWTJ.tar.gz
This will list the table of contents

bash$ tar zxvf C++Programming-HJWTJ.tar.gz
This will extract the files

O 8ead Lhe header flle flrsL and Lhen see Lhe example cpp program
o SLrlngh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/SLrlngh
o SLrlng8ufferh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/SLr
lng8ufferh
o SLrlng1okenlzerh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo
/SLrlng1okenlzerh
o SLrlng8Wh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/SLrln
g8Wh
o sLrlng_mulLlh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/sLr
lng_mulLlh
o example_SLrlngcpp hLLp//wwwangelflrecom/counLry/aldev0/cpphow
Lo/example_SLrlngcpp
O llle manlpulaLlon class only lengLh() funcLlon ls lmplemenLed
o llleh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/llleh
o lllecpp hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/lllecpp
O 1he zap() lmplemenLed here
o my_malloch hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/my
_malloch
o my_malloccpp hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/
my_malloccpp
O lmplemenLaLlon of sLrlng class
o SLrlngcpp hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/SLrlng
cpp
o SLrlng1okenlzercpp hLLp//wwwangelflrecom/counLry/aldev0/cpphow
Lo/SLrlng1okenlzercpp
o SLrlng8uffercpp hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/
SLrlng8uffercpp
o SLrlng8Wcpp hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/SLr
lng8Wcpp
O uebug faclllLles
o debugh hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/debugh
o debugcpp hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/debug
cpp
o Makeflle hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/Makefll
e
O Sample [ava flle for LesLlng Lhe funcLlonallLles of SLrlng class
o sLrlng[ava hLLp//wwwangelflrecom/counLry/aldev0/cpphowLo/sLrlng
[ava

You might also like